0

我有下面这个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');
4

1 回答 1

2

group1.findMember('addresses')中,K可以推断为"addresses",所以Person["addresses"]返回。

In group2.findMember('addresses'),K是来自顶级类声明的类型参数。当使用. keyof T_ T_ 所以你最终得到了返回类型,它是所有可能的属性值的联合。Kconst group2 = new Group2<Person>();Person["firstName" | "lastName" | "age" | "addresses"]

如果你使用const group2 = new Group2<Person, "addresses">(),结果应该是一样的。

于 2020-01-11T00:23:13.800 回答