使用泛型时,typescript条件不会产生任何结果 constfoo=()=>{ 类型a=T扩展字符串?真:假//工具提示显示类型a=T扩展字符串?真:假 const test1:a=true//类型“true”不可分配给类型“a”。(2322)
我认为typescript不会仅基于声明来解析函数声明的泛型。相反,它会等到看到函数实际如何调用后再解析泛型,即使在您的例子中,您已经定义了一个泛型,无论函数如何调用,它的计算结果始终为true 如果你有这个代码使用泛型时,typescript条件不会产生任何结果 constfoo=()=>{ 类型a=T扩展字符串?真:假//工具提示显示类型a=T扩展字符串?真:假 const test1:a=true//类型“true”不可分配给类型“a”。(2322),typescript,Typescript,我认为typescript不会仅基于声明来解析函数声明的泛型。相反,它会等到看到函数实际如何调用后再解析泛型,即使在您的例子中,您已经定义了一个泛型,无论函数如何调用,它的计算结果始终为true 如果你有这个代码 const foo =<T extends string>()=>{ type a = T extends string ? true:false // tooltip shows that type a = T extends string ? true
const foo =<T extends string>()=>{
type a = T extends string ? true:false // tooltip shows that type a = T extends string ? true : false
const test1:a = true // Type 'true' is not assignable to type 'a'.(2322) <===what!!
const test2:a = false // Type 'false' is not assignable to type 'a'.(2322) <===what!!
type b = unknown extends unknown ? true:false // tooltip shows that type b = true
const test3:b = true // <=== work at expected
const test4:b = false // Type 'false' is not assignable to type 'true'.(2322) <=== work as expected
}
constfoo=()=>{
类型a=T扩展字符串?真:假//工具提示显示类型a=T扩展字符串?真:假
让我们测试1:a
返回测试1
}
foo()
这里,当您将鼠标悬停在被调用的函数foo()上时,它会显示正确的返回类型true
,因为当它有一个被调用的函数时,TS会计算泛型。(上面的代码还有其他问题,但我相信它说明了这一点。)
const foo =<T extends string>()=>{
type a = T extends string ? true:false // tooltip shows that type a = T extends string ? true : false
let test1:a
return test1
}
foo()