typescript-is icon indicating copy to clipboard operation
typescript-is copied to clipboard

assertType throws errors on valid union null results

Open stevenlaidlaw opened this issue 5 years ago • 6 comments

const body: string | null = assertType<string | null>(null);

This simple test will cause a TypeGuardError to be thrown.

stevenlaidlaw avatar Aug 13 '20 07:08 stevenlaidlaw

A similar problem exists with null values in objects:

type test1 = {
    a?: number,
    b: string
};
type test2 = {
    a: null | number,
    b: string
};

const testObject1 = {
    a: null,
    b: 'asdf'
};
const testObject2 = {
    b: 'asdf'
};

console.log(is<test1>(testObject1), is<test1>(testObject2));
console.log(is<test2>(testObject1), is<test2>(testObject2));

output:

false true
false false

should be (as far as I know):

true true
true false

Pwuts avatar Sep 20 '20 13:09 Pwuts

hi @stevenlaidlaw and @Pwuts

I'm suspecting it has to do with the strictNullChecks option. Can you provide me with your compiler options / tsconfig.json?

woutervh- avatar Nov 25 '20 16:11 woutervh-

I've made a preliminary fix in v0.17.0 which hopefully addresses the | null issue with strictNullChecks: false. https://github.com/woutervh-/typescript-is/releases/tag/v0.17.0

Please let me know if it's working or not.

woutervh- avatar Nov 25 '20 18:11 woutervh-

it worked :tada:

ff-jkrispel avatar Dec 03 '20 15:12 ff-jkrispel

@woutervh- in reference to my previous comment:

with "strictNullChecks" omitted from my tsconfig.json:

false true
false false

with "strictNullChecks": true:

false true
true false

with "strictNullChecks": false:

true true
true false

The default of strictNullChecks is false (source), so the first and last result should be the same, right?

Some other possibly notable options from my tsconfig.json:

"target": "ES2020",
"allowSyntheticDefaultImports": true,
"lib": ["ES2020", "dom"],

Pwuts avatar Dec 06 '20 19:12 Pwuts

(Sidenote: I looked into fixing this myself and making a PR, but there was so much code and it seemed immensely complex; I didn't even know where to begin. If you can point me in a direction I might be able to contribute.)

Pwuts avatar Dec 29 '20 14:12 Pwuts