1

Consider the following example: (In strict-null-checks) mode

const fn: (p: { x: number } | null) => void = (p: { x: number }) => console.log(p.x);
fn(null);

This code produces no errors in typescript, but has a runtime type exception.

Seems to me like Typescript should have enforced target parameter type (here {x: number } | null) to be assignable to source parameter type (here { x: number }), so that, for example null wouldn't be passed where something else was expected and cause an error.

Why is this not enforcing that? Is that a bug in typescript? Or something in the configuration that I'm missing?

1

1 Answer 1

2

By default function parameters relate bi-variantly. This means that if the function is assignable if either the target parameter is a subtype of the source parameter or vice-versa (which is why this succeeds since { x: number } is a subtype of { x: number } | null

If you enable strictFunctionTypes parameters will relate contravariantly, this will mean that the assignment will succeed only if the target parameter is a subtype of source parameter. This will produce an error here since { x: number } | null is not a subtype of { x: number }

Enable strictFunctionTypes and you will get an error. You can see this behavior in the playground too: with the option and without the option

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.