Home > other >  Typescript inferring defined value as undefined
Typescript inferring defined value as undefined

Time:10-05

I have the below array which can have either be an object or undefined. Even after filtering the results to contain all defined values, typescript still says it could be undefined

interface Bob {
    name: string;
}

type BobDetails = undefined | Bob;

const myArray: BobDetails[] = [{ name:  "Bob"}, undefined];
myArray[0].name; // expected Object is possibly 'undefined'.(2532)

var filter = myArray.filter(arr => arr?.name);
filter[0].name; // still Object is possibly 'undefined'.(2532)

How do make Typescript know that filter[] will have only Bob[] and no undefined. I am aware we might be able to do with ! but I want the normal flow to realise it.

Typescript Playground Example

CodePudding user response:

To do that, you need to have your filter function be a custom type guard. Right now, arr => arr?.name is just a function that returns a string | undefined. You and i can figure out what implications that will have for the resulting array, but typescript needs a bit more.

If you change the function so that it returns a boolean, and you give it the special return type arr is Bob, then typescript knows that if true is returned, then it can deduce that arr is a Bob. And the filter method knows that this will then result in a Bob[]:

var filter = myArray.filter((arr): arr is Bob => arr?.name !== undefined);

Playground link

CodePudding user response:

Imagine the array being: BobDetails[] = [undefined, undefined];

Then filter[0].name; will also be undefined. For simplicity you can check the length of filter as:

if(filter.length>0){ filter[0].name; ... your code}

CodePudding user response:

you get the error "Object is possibly undefined", because the type you specified says so. type BobDetails = undefined | Bob. The type of the array myArray is array of BoBDetails which is either bob or undefined.

Remove undefined type. As type BobDetails = Bob and remove the undefined value from the array.

  • Related