【发布时间】:2021-01-30 18:43:27
【问题描述】:
假设我们有一个参数是字符串的函数
const action = (param: string) => {
return param;
};
还有一个泛型类型
interface Relation<T, K extends keyof T> {
store: T;
storeKey: K;
}
接受Relation 类型参数并执行action 的函数
const testFunction = <T, K extends keyof T>({ store, storeKey }: Relation<T, K>) => {
action(store[storeKey]);
};
现在 TypeScript 错误消息是 store[storeKey] is not assignable to type string,我明白为什么。如果T[K] 不是字符串(没有类型保护,只有静态类型检查),有什么方法可以“弃用”testFunction 的调用?
UPD:T 不仅可以有字符串属性
【问题讨论】:
标签: typescript types typescript-typings