Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 561
Bussiere Avatar asked Nov 22 '25 22:11

Bussiere


1 Answers

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]);
like image 185
Murat Karagöz Avatar answered Nov 28 '25 15:11

Murat Karagöz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!