所以,我对这个看似微不足道的例子感到非常困惑。 我正在根据博客文章 here 测试条件类型,但无法编译代码段。我不明白我做错了什么
function processO< T extends string | null>(test: T): T extends string ? string : null {
return test && test.replace(/f/g, "p")
}
processO("foo").toUpperCase()
这是 Typescript 的错误
a.ts:2:5 - error TS2322: Type 'string' is not assignable to type 'T extends string ? string : null'.
2 return test && test.replace(/f/g, "p")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
为什么 string
不能分配给 T extends string ? string : null
。我是否缺少 declare
块或过载?
编辑:看起来这是一个众所周知的限制和文档,提供了替代方案 here