【问题标题】:passing in a property key as a generic argument in typescript将属性键作为打字稿中的通用参数传递
【发布时间】:2021-05-24 14:32:26
【问题描述】:

这是codesanbox,这是代码:

type Tags = "TAG1" | "TAG2";

export type S<Tag extends Tags> = {
  tag: Tag;
  get<K, R>(k: K): R;
};

const store = {
  one: "ONE"
};

type Keys = keyof typeof store;

const s: S<"TAG1"> = {
  tag: "TAG1",
  get<K extends Keys>(k: K) {
    return store[k];
  }
};

get&lt;K extends Keys&gt;(k: K) { 出现错误

Type '(k: K) => { one: string; }[K]' 不可分配给类型 '(k: K) => R'。 参数“k”和“k”的类型不兼容。 类型 'K' 不可分配给类型 '"one"'.ts(2322

我可以输入这样的键值吗?

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    只是不要使用泛型作为返回类型

    type Tags = "TAG1" | "TAG2";
    
    export type S<Tag extends Tags> = {
      tag: Tag;
      get<K extends Keys>(k: K): Store[K];
    };
    
    const store = {
      one: "ONE"
    };
    
    type Store = typeof store
    type Keys = keyof typeof store;
    
    const s: S<"TAG1"> = {
      tag: "TAG1",
      get<K extends Keys>(k: K):Store[K] {
        return store[k];
      }
    };
    
    const x = s.get('one') // string
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2022-11-26
      • 2020-06-22
      • 1970-01-01
      • 2021-08-31
      • 2022-12-18
      • 1970-01-01
      相关资源
      最近更新 更多