我有下面这个K extends keyof T
声明 where 的简单例子,但是推断的返回类型的结果findMember
却不同,我真的不明白为什么会有这样的差异。
我还在这里创建了一个指向 TypeScript Playground 的链接
class Group1<T> {
findMember<K extends keyof T = keyof T>(name: K): T[K] {
return {} as T[K];
}
}
class Group2<T, K extends keyof T = keyof T> {
findMember(name: K): T[K] {
return {} as T[K];
}
}
interface Person {
firstName: string;
lastName: string;
age: number;
addresses: Array<{
street: string;
city: string;
zip: string;
}>
}
const group1 = new Group1<Person>();
// Inferred type is Array<{ street: string; city: string; zip: string; }>;
const addresses1 = group1.findMember('addresses');
const group2 = new Group2<Person>();
// Inferred type is string | number | Array<{ street: string; city: string; zip: string; }>;
const addresses2 = group2.findMember('addresses');