首页 > 解决方案 > 在 TypeScript 中,我可以根据索引器键的窄类型来限制索引器值的类型吗?

问题描述

标签: typescript

解决方案


我也一直在寻找这个。我在 TypeScript 中进行了一些实验,并提出了这个解决方案:

type ObjectWithKey<obj extends {[key: string]: any}> = {
  [k in keyof obj]: {key: k};
}

declare function createObjectWithKeys<T extends {[key: string]: any} & ObjectWithKey<T>>(input: T): T;

// This does not compile
const x = createObjectWithKeys({
    a: 1,
    b: {key: 'c'},
    c: {key: false}
})

// This does compile
const x = createObjectWithKeys({
    a: {key: 'a'},
    b: {key: 'b'},
    c: {key: 'c'}
})

推荐阅读