Bussiere
Bussiere

Reputation: 1152

Precise the value of a multiple type in an interface in typescript :

Here is my code (in typescript 2.3.4) :

type TokenType =  "operator" | "doubleQuote" | "identifier" | "(end)";



interface Token {
    type: TokenType;
    value: string;
    pos: number;
}

interface PosTokenOp {
    type: "operator" | TokenType ;
    value: string;
    pos: number;
    left: Token | null;
    right: Token | null;
}

So i would like that PostTokenOp type would be just :

interface PosTokenOp {
    type: "operator" ;
    value: string;
    pos: number;
    left: Token | null;
    right: Token | null;
}

But if i put only "operator" it don't recognize that it's a part of TokenType and i have error in my code.

So i would like to make type of PostTokenOp equal to "operator" and precise that operator is one of the value of TokenType.

If anyone have any idea on how to do that.

Thanks and regards

Upvotes: 3

Views: 3735

Answers (1)

Murat Karagöz
Murat Karagöz

Reputation: 37604

If you can upgrade to Typescript 2.4 you can use String Enums.

e.g.

enum TokenType{"operator", "doubleQuote", "identifier", "(end)"}

interface Token {
    type: TokenType;
    value: string;
    pos: number;
}

interface PosTokenOp {
    type: TokenType.operator ;
    value: string;
    pos: number;
    left: Token | null;
    right: Token | null;
}

Before 2.4 you can use the normal Enums e.g.

enum TokenType { operator, doubleQuote ,identifier , end}

interface Token {
    type: TokenType;
    value: string;
    pos: number;
}

interface PosTokenOp {
    type: TokenType.operator;
}

And the usage is like this then

 test:PosTokenOp = {
       type: TokenType.operator
    }
 console.log(TokenType[this.test.type]);

Upvotes: 3

Related Questions