假设我有这个:
type KeyForValueType<T, ValueType> = { [K in keyof T]: T[K] extends ValueType ? K : never; }[keyof T];
declare function fn1<T, ValueType>(obj: T, key: KeyForValueType<T, ValueType>): void;
fn1
将按预期工作,它将根据该键的值类型适当限制我可以使用的键:
fn1<{ a: number; b: string }, string>({ a: 11, b: 'str' }, 'a'); // error as expected
fn1<{ a: number; b: string }, string>({ a: 11, b: 'str' }, 'b'); // works
fn1<{ a: number; b: string }, number>({ a: 11, b: 'str' }, 'a'); // works
fn1<{ a: number; b: string }, number>({ a: 11, b: 'str' }, 'b'); // error as expected
我从这里得到了以上内容:https://stackoverflow.com/a/51476941/520229
但是,在实际实现该功能时,我无法使其识别值的类型:
// with generic ValueType
function fn2<T, ValueType>(obj: T, key: KeyForValueType<T, ValueType>): void {
const value: ValueType = obj[key];
console.log(value);
}
// or even fixed value type
function fn3<T>(obj: T, key: KeyForValueType<T, string>): void {
const value: string = obj[key];
console.log(value);
}
签出here。
我在这里做错什么了吗?甚至可能与打字稿有关?