【问题标题】:How to define return type using keyof accessor with TypeScript?如何使用带有 TypeScript 的 keyof 访问器定义返回类型?
【发布时间】:2020-01-13 14:53:35
【问题描述】:

是否可以创建一个使用keyof 访问对象属性并让 TypeScript 推断返回值的函数?

interface Example {
    name: string;
    handles: number;
}

function get(n: keyof Example) {
   const x: Example = {name: 'House', handles: 8};
   return x[n];
}

function put(value: string) {

}

put(get("name"));
// ^^^ Error: Argument of type 'string | number' is not assignable to parameter of type 'string'

TypeScript 将所有允许的类型合并在一起,但是当使用值 "name" 调用函数时,它不会推断类型是 string

我可以通过转换类型来解决问题。

put(get("name") as string);

有没有办法在不强制转换的情况下做到这一点?

【问题讨论】:

    标签: javascript typescript generics casting


    【解决方案1】:

    当然,你只需要将 get generic 设为不返回所有可能输出类型的联合:

    function get<K extends keyof Example>(n: K) {
      const x: Example = { name: "House", handles: 8 };
      return x[n];
    }
    

    现在推断签名为:

    // function get<K extends "name" | "handles">(n: K): Example[K]
    

    返回类型Example[K]lookup type,表示当您使用键K 索引Example 时获得的类型。

    当你调用它时,K 被推断为字符串文字类型,如果可以的话:

    get("name"); // function get<"name">(n: "name"): string
    

    Example["name"] 等价于string。所以现在你的电话可以正常工作了:

    put(get("name")); // okay
    

    希望对您有所帮助。祝你好运!

    Link to code

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多