【发布时间】:2020-06-30 21:19:16
【问题描述】:
我有一个这样定义的缓存(sn-p):
interface Cache {
chapterDates: { [workId: string]: string[] };
kudosChecked: number[];
}
export const DEFAULT_CACHE: Cache = {
chapterDates: {},
kudosChecked: [],
};
我希望能够定义一个函数,当给定一个像“chapterDates”或“kudosChecked”这样的缓存键作为字符串时,它将返回缓存的值,以及该属性的正确类型。
到目前为止,我已经尝试了以下使用条件类型:
type Test<T> = T extends 'chapterDates'
? { [workId: string]: string[] }
: T extends 'kudosChecked'
? number[]
: never;
export async function getCache<T extends keyof Cache, R extends Test<T>>(
id: T
): Promise<R> {
[...]
}
我也试过这个:
export async function getCache<
T extends keyof Cache,
R extends Cache[T]
>(id: T): Promise<R> {
[...]
}
没有解决方案似乎让 typescript 明白,当返回类型为 e.g. getCache('kudosChecked') 应该是 number[]。目前似乎认为是number[] | { [workId: string]: string[] }。
我是完全错误的还是什么,我对打字稿很陌生?
【问题讨论】:
标签: typescript