Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29097

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?

Upvotes: 4

Views: 3446

Answers (5)

Maciej Sikora
Maciej Sikora

Reputation: 20132

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']

Upvotes: 9

toskv
toskv

Reputation: 31600

You have 2 options.

1 extract the type of the field type as it's own type and use it in both places.

type ObjectType = 'AA' | 'AZ' | 'XY'
interface A {
  type: ObjectType;

}
interface B {
  type: ObjectType
}

Or if you can not modify the first interface, you can make the second interface extend a subtype of the first one.

interface A {
  type: 'AA' | 'AZ' | 'XY';

}

interface B extends Pick<A, 'type'> {

}

Upvotes: 1

DaggeJ
DaggeJ

Reputation: 2191

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;
}

Upvotes: 2

Chris Pickford
Chris Pickford

Reputation: 8991

You could create a new interface that contains only the type property definition, then extend from that in your others:

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

export interface IMyObj extends ITypedObj {
    id: string;
}

TS Handbook: Extending Interfaces

Upvotes: 1

Richard Price
Richard Price

Reputation: 490

you can use the extends functionality

so you would have

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

and then

export interface IMyOtherObj extends IMyObj{
    ...
    otherthings: string;
    ...
}

Upvotes: 0

Related Questions