TypeScript ignores optional parameter of type never

I don't want a certain function to be passed as a parameter to another function, however, according to TypeScript, it is valid, but is it? and why?

Here's some sample code:

function spoken(nope?: never): void {
    console.log("He has spoken.");
}

function speak(toSay: string, spoken: (arg1: string) => void): void {
    console.log("He says: " + toSay);
    spoken("He has spoken.");
}

speak("Hello world.", spoken);

      

Because basically, TypeScript says that the type string is assigned to type never, because if nope did not specify a type number, TypeScript will complain because the type string is incompatible with the type number.

+1


source to share


1 answer


Short answer

... according to TypeScript really, but right? and why?

Yes, that is true, because TypeScript says that a type never

can be assigned to a type string

. Below is some code in typescript / play .

Details of never

The basic types documentation says:

A type is never a subtype and is assigned to each type; however, no type is a subtype or is never assigned (other than itself).

This means that we can assign never

to string

, but cannot assign string

to never

.



let arg1: string = (null as never); // works
let arg2: never = (null as string); // fails

      

Details of your situation

Your function speak

has a named parameter spoken

, which is a function with a arg1

type parameter string

. Here is the parameter spoken

by itself.

let spokenParam: (arg1: string) => void;

      

Since it arg1

is string

and string

is a supertype never

, the following assignment is performed.

function spoken(nope?: never): void {
    console.log("He has spoken.");
}

spokenParam = spoken;

      

+1


source







All Articles