faerin
faerin

Reputation: 1925

Interface with dynamic and static properties

I've got a question regarding a more dynamic kind of interface where dynamic and static properties can be used together - even if they are of different types. Is this possible? If yes, does it make any sense at all?

Let's say I want something like this.

type MyCustomType = {
    foo: string;
};

export interface MyInterface {
    [key: string]: MyCustomType;
    bar: string;
};

I want to make sure that a certain prop (that I do not know the name of in advance) points to a value of type MyCustomType. The rest of the properties in MyInterface I do know the names of and they point to other types.

The above code results in the following error:

Property 'bar' of type 'string' is not assignable to string index type MyCustomType.

I could get around that by using either intersection (as the below example) or any however.. that will also affect my dynamic prop and ruin guarantees of it's type.

export interface MyInterface {
    [key: string]: MyCustomType | string;
    bar: string;
};

Any suggestions are much appreciated :)

Upvotes: 2

Views: 634

Answers (1)

Ali Nasserzadeh
Ali Nasserzadeh

Reputation: 1449

This can be done in the following way, using an intersection:

type MyCustomType = {
    foo: string;
};

type MyInterface = {
    [key: string]: MyCustomType;
} & { bar: string };

In order for intersections to work MyInterface has to be a type.

Upvotes: 5

Related Questions