我有以下的类和函数:

class Test {
  prop: string;
  otherProp: number;

  constructor() {
    const result = doSomething<Test>('prop');
  }
}

function doSomething<T>(propName: keyof T): ???? {
  // ,,,
}

有一种方法,可以从函数中返回与函数所获得的属性相同的类型。在上面的例子中,返回类型应该是string。如果我用otherProp调用它,返回类型应该是number。

最佳答案

您需要一个额外的类型参数来捕获传入的密钥的实际类型(我们称之为K)。然后可以使用K索引到T(即使用类型查询)

class Test {
    prop: string;
    otherProp: number;

    constructor() {
        const result = doSomething(this, 'prop');
    }
}

function doSomething<T, K extends keyof T>(target: T, propName: keyof T): T[K] {
    return this[propName];
}

我修改了上面的例子,将一些参数传递给了T类型,以从参数推断出KT。Type Script不支持部分类型推断,因此我们不能指定T并推断出K。所以如果我们没有一个类型的参数T我们需要写:
class Test {
    prop: string;
    otherProp: number;

    constructor() {
        const result = doSomething<Test, 'prop'>('prop');
    }
}

function doSomething<T, K extends keyof T>(propName: keyof T): T[K] {
    return this[propName];
}

一个更好的版本S使用一个函数TaHT返回一个函数,并且在第一个调用中具有T固定,并且在第二个调用中推断出K
class Test {
    prop: string;
    otherProp: number;

    constructor() {
        const result = doSomething<Test>()('prop');
    }
}

function doSomething<T>() {
    return function <K extends keyof T>(propName: keyof T): T[K] {
        return this[propName];
    }
}

10-05 20:51
查看更多