这是一个 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 '
我可以输入这样的键值吗?
答案 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