Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
Writing a function that returns an array of type "without null" throws an error Type 'T' is not assignable to type 'NonNull'.(2322)

Following this answer, I have a function that removes null elements from an array (but not undefined):

// JavaScript
const dropNull = arr => {
    return arr.flatMap((f) => (f === null ? [] : f));
};

And now I want to use TypeScript to strictly define the types of the function's input and output:

  • input: any array
  • output: any array that doesn't contain null

This answer shows a very similar situation, but opposite to mine: whereas they want to allow null but restrict undefined, I want to restrict null and allow undefined. So inspired by the answer I did the reverse tweak:

type NonNull<T> = T extends null ? never : T[];

const dropNull = <T>(arr: T[]): NonNull<T>[] => {
    return arr.flatMap((f) => (f === null ? [] : f));
};

But as this REPL shows, I get an error:

Type 'T[]' is not assignable to type 'NonNull[]'.
Type 'T' is not assignable to type 'NonNull'.(2322)

Researching this error I've seen answers such as this one, but I couldn't figure out how to adopt it to my case.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It's hard for typescript to enforce returning a conditional type, because it's hard to know how your logic corresponds to that type. But I think you're over complicating it, and you can sidestep the issue entirely.

const dropNull = <T>(arr: (T | null)[]): T[] => {
    return arr.flatMap((f) => (f === null ? [] : f));
};

Here the generic parameter T is inferred as a type that does not contain null. And the argument is an array that can be filled with T or null.

Then you can simply return non null values from the array and typescript is happy.

const numsOrNull = [1,2,null] // (number | null)[]
const nums = dropNull(numsOrNull) // number[]

Playground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!