在打字稿中将属性键作为通用参数传递

时间:2021-02-22 10:44:51

标签: typescript

这是一个 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<K extends Keys>(k: K) { 出现错误

<块引用>

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

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

1 个答案:

答案 0 :(得分:0)

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

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