4

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?

1
  • 2
    is it not possible to just extract those as a type? Commented Mar 24, 2020 at 14:02

5 Answers 5

9

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']
Sign up to request clarification or add additional context in comments.

1 Comment

What if I need something like X and the interface has a property which is X[]? Is extracting the type of X still possible? As this method would then return X[].
2

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

Comments

1

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

Comments

1

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

}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.