Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - how to: property starting with a "." (dot)

Tags:

typescript

When calling a .NET OAuthToken Endpoint the result contains two properties starting with a ".":

{   
    "access_token":"abcde..."
    "expires_in":1209599
    ".expires":"Fri, 16 May 2014..."    <- this
    ".issued":"Fri, 02 May 2014..."     <- this
    ... more properties ...
}

What I like to do is create an interface in TypeScript to handle this result. However I do not know how to declare these two properties with the little dot in front.

export interface Token {
    access_token: string;
    expires_in: number;
    .expires???
    .issued???
}

Any idea?

like image 883
okieh Avatar asked May 02 '14 13:05

okieh


People also ask

What is dot in TypeScript?

The question mark dot (?.) syntax is called optional chaining in TypeScript and is like using dot notation to access a nested property of an object, but instead of causing an error if the reference is nullish, it short-circuits returning undefined .

How do I add a property in TypeScript?

To add a property to an object in TypeScript, set the property as optional on the interface you assign to the object using a question mark. You can then add the property at a later point in time without getting a type error. Copied!

How do you access the properties of an object in TypeScript?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

What is property in TypeScript?

Property in TypeScript A property of a function type for each exported function declaration. A property of a constructor type for each exported class declaration. A property of an object type for each exported internal module declaration.


2 Answers

Viewing section 3.7.1 of the TypeScript language specification, it looks like property signatures in object literals work about the same as object literal property definitions in JavaScript, meaning a property name can be an identifier, a string literal, or a numeric literal. In other words, you can simply do:

export interface Token {
    access_token: string;
    expires_in: number;
    ".expires": string;
    ".issued": string;
}
like image 145
JAB Avatar answered Sep 28 '22 06:09

JAB


Just use quoted interface members :

interface Token {
    access_token: string;
    expires_in: number;
    '.expires': number;
}

var foo:Token;
foo['.expires'] = '123'; // Error 
foo['.expires'] = 123; // okay 
like image 20
basarat Avatar answered Sep 28 '22 07:09

basarat