我有这个脚本:
type Input = string
function util(input: Input) {
return input
}
function main(input: Input | null) {
const isNull = input === null
if (isNull) {
return 'empty string'
}
input = util(input) //error
}
错误是:Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.
但是,如果出现以下情况,则不会发生:
- 最后一行是
return util(input)
, 或 - 条件线缩短为
if (input === null)
这是为什么?
这可能看起来违反直觉 - 在我看来 - 但 Typescript 不能使用中间变量来推断用于为该变量赋予值的值的类型。
您需要使用
if (input === null)
或编写并使用类型谓词isNull
。编辑:
这是使用类型谓词的样子:
不过,我不确定它是否会为简单的写作添加任何内容
if (value === null)
。