【发布时间】:2021-03-21 14:35:18
【问题描述】:
考虑以下代码 (TS Playground):
function identity<T>(value: T): T {
if (typeof value === 'string') {
return value.replace('foo', 'bar'); // <-- ERROR
}
return value;
}
导致错误Type 'string' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'string'.
似乎类型保护不足以缩小泛型参数的类型并执行字符串操作。
为什么会出现这个错误,我该如何解决?
【问题讨论】:
标签: typescript typescript-generics