Skip to content

Instantly share code, notes, and snippets.

@ralph
Last active June 21, 2023 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralph/c33ffd92b6b67751dbb06efb88282031 to your computer and use it in GitHub Desktop.
Save ralph/c33ffd92b6b67751dbb06efb88282031 to your computer and use it in GitHub Desktop.
I am trying to convince typescript that an item cannot be `null` / `undefined` when using a filter, but typescript does not trust me. Am I missing something? Is typescript stupid, or am I? 🤔 The only way I could get this working is by force-casting a type with `as`. Can you suggest a more elegant way?
src/test.ts:10:39 - error TS18049: 'item' is possibly 'null' or 'undefined'.
10 strings.forEach((item) => console.log(item.id, item.label))
~~~~
src/test.ts:10:48 - error TS18049: 'item' is possibly 'null' or 'undefined'.
10 strings.forEach((item) => console.log(item.id, item.label))
~~~~
Found 2 errors in the same file, starting at: src/test.ts
const stringsAndNull = [
{ id: 1, label: 'foo' },
{ id: 2, label: 'bar' },
null,
{ id: 3, label: 'test' },
undefined,
{ id: 3, label: 'lol' },
]
const strings = stringsAndNull.filter((item) => item != null)
strings.forEach((item) => console.log(item.id, item.label))
src/test.ts:10:17 - error TS2345: Argument of type '(item: { id: number; label: string;}) => void' is not assignable to parameter of type '(value: { id: number; label: string; } | null | undefined, index: number, array: ({ id: number; label: string; } | null | undefined)[]) => void'.
Types of parameters 'item' and 'value' are incompatible.
Type '{ id: number; label: string; } | null | undefined' is not assignable to type '{ id: number; label: string; }'.
Type 'undefined' is not assignable to type '{ id: number; label: string; }'.
10 strings.forEach((item: { id: number, label: string}) => console.log(item.id, item.label))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const stringsAndNull = [
{ id: 1, label: 'foo' },
{ id: 2, label: 'bar' },
null,
{ id: 3, label: 'test' },
undefined,
{ id: 3, label: 'lol' },
]
const strings = stringsAndNull.filter((item) => item != null)
strings.forEach((item: { id: number, label: string }) => console.log(item.id, item.label))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment