Language-tools: Why is a required prop's type "T | undefined" with strictNullChecks enabled?

Created on 1 Mar 2021  路  2Comments  路  Source: sveltejs/language-tools

Say you have the following component (it's using TypeScript, of course):

MyComponent.svelte:

<script lang="ts">
    export let label: string;
</script>
...

As you can see, the label prop is required, I have not supplied a default value and thus it's considered a required prop.
Now, if I have strictNullChecks set to true in my tsconfig.json file, I expect a required component prop like label in this case to not be able to receive null or undefined unless I explicitly specify that in their type.

tsconfig.json:

"compilerOptions": {
    "strictNullChecks": true
}

However, Svelte appears to make the type of the label prop string | undefined behind the scenes, and that means the consumer of this component could pass undefined as the value of label, which obviously defeats the whole purpose of enabling strictNullChecks in the first place.

<MyComponent label={undefined} /> <!-- No error! Even though "strictNullChecks" is "true" + the type of "label" is "string" -->

Most helpful comment

This is a decision from the early days that bites us now. Essentially, we decided to make props optional if the strict compilerOption is not set. I'd very much like to revisit this decision and change it so that properties that have no initializer are treated as being required, which would make this work as expected for you (no | undefined).

All 2 comments

This is a decision from the early days that bites us now. Essentially, we decided to make props optional if the strict compilerOption is not set. I'd very much like to revisit this decision and change it so that properties that have no initializer are treated as being required, which would make this work as expected for you (no | undefined).

@dummdidumm

I'd very much like to revisit this decision and change it so that properties that have no initializer are treated as being required, which would make this work as expected for you (no | undefined).

I think that would be great and it makes MUCH more sense that way. The current approach obviously causes unexpected behavior with TypeScript's strict type-checking options enabled.
Thank you.

Was this page helpful?
0 / 5 - 0 ratings