any
尽管我知道实现是正确的。
type ExportType<InputType extends string|undefined> =
string extends InputType ? undefined : ()=>void;
function convert<InputType extends string|undefined>(input: InputType): ExportType<InputType>;
(我知道我可以使用重载,但我真正的问题更复杂,对于真正的问题重载不现实)
实际上,签名的意思是“如果参数是
string
,我会回来的
()=>void
undefined
,我会回来的
未定义
.
convert("x")
和
convert(undefined)
表明typescript符合这个定义。
type ExportType<InputType extends string|undefined> =
string extends InputType ? undefined : ()=>void;
function convert<InputType extends string|undefined>(input: InputType): ExportType<InputType> {
if (input) {
return ()=>{console.log("OK");};
} else {
return undefined;
}
}
这不会编译。打字本上写着:
error TS2322: Type '() => void' is not assignable to type 'ExportType<InputType>'.
return ()=>{console.log("OK");};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
但那条线在
if (input)
未定义
,所以一定是这样
() => void
... 但编译器似乎还不够聪明,无法看到这一点。
return <any>(()=>{console.log("OK");});
使它工作,但它令人失望。。。