基于类属性的 typescript 函数返回类型

标签 typescript

我有以下类和函数:

class Test {
  prop: string;
  otherProp: number;

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

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

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

最佳答案

您需要一个额外的类型参数来捕获传入的键的实际类型(我们称之为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。 Typescript 不支持部分类型推断,因此我们无法指定 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];
    }
}

关于基于类属性的 typescript 函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54365283/

相关文章:

javascript - webpack 4.1.1 -> configuration.module 有一个未知的属性 'loaders' 。

javascript - 在指令内手动从注入(inject)器获取依赖项

Angular SVG 圆形进度条不适用于 Ionic

angular - 什么时候在 Angular 项目中使用类或接口(interface)?

javascript - TypeScript 通过 tsc 命令 : Output to single file without concatenation

javascript - 不可变 typescript 类型定义 : why is concat operating on any?

javascript - 为什么 Object.keys(this).map(key => (this as any)[key])?

javascript - 从数组中删除项目 - Angular 4

javascript - Angular Google map 组件 TypeError : Cannot read property 'nativeElement' of undefined

enums - 如何在 TypeScript 中创建类似类型的枚举?