我想做一个既能接收string | undefined
又能返回string | undefined
的函数.这是我的第一个方法:
sanitizeName: (name: string | undefined): string | undefined => {
return name?.replace(...)
},
但是,当我使用字符串参数调用此函数时,我知道它肯定也会返回string
,但现在类型是string | undefined
,我需要额外的存在判断.
我try 的是赋值为string | undefined
的泛型T
,它是参数和返回类型:
sanitizeName: <T extends string | undefined>(name: T): T => {
return name?.replace(...)
},
在我看来,这应该是可行的:如果函数收到UNDEFINED,它就会返回UNDEFINED.如果它接收到字符串,则返回一个字符串.
但我得到了这样的错误:
Type 'string | undefined' is not assignable to type 'T'.
'string | undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | undefined'.
Type 'undefined' is not assignable to type 'T'.
'undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | undefined'.ts(2322)
为什么会这样呢?我如何才能获得所需的行为(string
返回string
,undefined
返回undefined
)?