jbccollins
jbccollins

Reputation: 1042

Is it possible to enforce the same dynamic keys between interfaces in TypeScript?

Given an interface MyInterface1 with a dynamic set of keys:

Is it possible to pull the keys from MyInterface1 to be used as keys in MyInterface2?

Something like:

export interface MyInterface1 {
    [key: string]: string
}

export interface MyInterface2 {
  [k in keyof MyInterface1]: string, // This line doesnt work :(
}

I saw some discussion of stuff like this here: https://github.com/Microsoft/TypeScript/issues/5683#issuecomment-376505064

Upvotes: 0

Views: 29

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30879

You need to declare a type alias, not an interface:

export type MyInterface2 = {
  [k in keyof MyInterface1]: string
};

Upvotes: 1

Related Questions