Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use one property of a Typescript interface in an other interface

Suppose I have a Typescript Interface as follows

export interface IMyObj {
    id: string;
    type: 'AA' | 'AZ' | 'XY';
    ...
}

Now I need an other interface which also has that type field

export interface IMyOtherObj {
    ...
    type: 'AA' | 'AZ' | 'XY';
    ...
}

As you can see I have duplicated the values of type. So my question is, how can I reuse IMyObj.type in my IMyOtherObj interface? I tried this

export interface IMyOtherObj {
    ...
    type: IMyObj.type; // -> error
    ...
}

I think I'm close but so far no luck, any suggestions?

like image 597
Jeanluca Scaljeri Avatar asked Nov 07 '25 18:11

Jeanluca Scaljeri


2 Answers

Your issue is that TS type system has no . property access but indexed property type, change one thing in your type definition:

type: IMyObj['type']
like image 152
Maciej Sikora Avatar answered Nov 09 '25 10:11

Maciej Sikora


Define an enumeration for your property type, such as

enum MyEnum {
    Aa = "AA",
    Az = "AZ",
    Xy = "XY"
}

and use it like this;

export interface IMyObj {
    id: string;
    type: MyEnum;
}
like image 38
DaggeJ Avatar answered Nov 09 '25 09:11

DaggeJ