简体   繁体   中英

Return type should define callback param type

Why is the parameter children is unknown[] ??

It should be inferred as string[] because I am returning 'asdf' and my function definition is: mapFunction: (children: K[]) => K,)

类型

What I am doing wrong ?

function returnTypeDefinesParamType<K>(mapFunction: (children: K[]) => K,):void{
    // ... some code
}
returnTypeDefinesParamType( (children)=>{
    return 'asdf';
})

I'd say this is an instance of microsoft/TypeScript#31146 ; the compiler tries to contextually type children before it has a type for the full callback and before it can infer K (this is an unconventional name btw, K usually indicates key-like types; consider just T here), and it can't do it. The inference fails, K becomes the widest possible type: unknown . That isn't necessarily wrong , since without annotations children => "asdf" is assignable to (children: unknown[]) => unknown , but it's not useful to you. That issue in GitHub is labeled as a bug but it's not clear whether something will be done about it; I'd expect this is more of a design limitation.

In any case if you want to work around it you will need to manually annotate or specify types somewhere. One way to do this is to annotate the callback parameter:

returnTypeDefinesParamType((children: string[]) => {
    return 'asdf';
});

or you could manually specify the type parameter:

returnTypeDefinesParamType<string>((children) => {
    return 'asdf';
}); 

Either way you're going to be stuck spelling things out to the compiler to make up for a limitation in its inference abilities.

Playground link to code

returnTypeDefinesParamType<string>( (children)=>{
return 'asdf';
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM