我想创建一个 TypeScript 函数,该函数接受一个对象和该对象内的一个属性,其值为 a string。使用<T, K extends keyof T>工作来确保只T允许键作为属性的值,但我似乎无法缩小范围,以便键也必须指向 type 的属性string。这可能吗?
我试过这个:
function getKey<T extends {K: string}, K extends keyof T>(item: T, keyProperty: K): string {
return item[keyProperty];
}
但它只是说Type 'T[K]' is not assignable to type 'string'。为什么T extends {K: string}约束不能确保它T[K]实际上是 a string,或者更确切地说,提供的K必须满足条件,所以它T[K]是 a string?
为了清楚起见,我希望能够像这样调用这个函数:
getKey({foo: 'VALUE', bar: 42}, 'foo') => return 'VALUE';
getKey({foo: 'VALUE', bar: 42}, 'bar') => should not be allowed since 'bar' is not a string property of the supplied object
getKey({foo: 'VALUE', bar: 'ANOTHER VALUE'}, 'bar') => return 'ANOTHER VALUE'