首页 > 解决方案 > 是否可以在 TypeScript 中的接口之间强制执行相同的动态键?

问题描述

给定一个MyInterface1带有一组动态键的接口:

是否可以从中拉出钥匙MyInterface1以用作钥匙MyInterface2

就像是:

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

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

我在这里看到了一些这样的讨论:https ://github.com/Microsoft/TypeScript/issues/5683#issuecomment-376505064

标签: typescript

解决方案


您需要声明类型别名,而不是接口:

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

推荐阅读