#Typescript doesn't infer type from array.filter() function

17 messages · Page 1 of 1 (latest)

sleek echo
#
const startedTests = tests.filter(test => test.thread_id !== null);

tests if of type

{
  thread_id: string | null
}[]

But after the filter() operation

for (
  const thread of startedTests.reduce((accumulator, currentValue) => {
    accumulator.push(currentValue.thread_id); // Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.
    return accumulator;
  }, (<string[]> []))
) {
     // code   
}

Why is typescript considering thread_id as possibly null if tests with a null thread_id value are filtered out?

zenith idol
#

You need to annotate it as a predicate:

const startedTests = tests.filter((test): test is string => test.thread_id !== null)
sleek echo
zenith idol
#

Oh you are right.

#

You can do test is { thread_id: string }.

sleek echo
#

it doesn't work

#

this works

accumulator.push(currentValue.thread_id as string);
zenith idol
#

It does work.

mild spadeBOT
#
declare const tests: {
    thread_id: string | null
}[]

const startedTests = tests.filter((test): test is { thread_id: string } => test.thread_id !== null)
//    ^? - const startedTests: {
//        thread_id: string;
//    }[]
sleek echo
zenith idol
#

No, you generally do not want type assertions, they are unsafe.

sleek echo
#

so from my understanding the predicate will change the variable's type to the test type if compatible, right?

zenith idol