Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typescript array not assignable after map and find

The following code

const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i));

This causes an error "Type ‘(string | undefined)[]’ is not assignable to type ‘string[]’." as find gives string | undefined. So I was hoping adding a filter can fix that, like:

const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i)).filter(i => i);

But this didn’t work, why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TS version 4.2.3

>Solution :

If you know for sure that the find call here will never return undefined, you can use an assertion with ‘!’:

const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i)!);
//                                                                   ^

Otherwise you will have to write a guard:

function isDefinitelyAString(val: unknown): val is string {
    return typeof val === "string";
}

const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i)).filter(isDefinitelyAString);

You can also inline the guard like @jonrsharpe suggests:

const s: string[] = ["x", "y", "z"].map(i => ["x"].find(t => t === i)).filter((i): i is string => typeof i === "string");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading