I have a collection of data that looks like this:
interface Item {
name: "one" | "two";
data: string;
}
const namedItems: Item[] = [
{
name: "one",
data: "some data one",
},
{
name: "two",
data: "some data two",
},
];
Each item has a name and the value can either be "one" or "two".
Then running an array find on this:
const getData = (query: "one" | "two") =>
namedItems.find((item): boolean => query === item.name).data;
Throws a typescript error "Object is possibly 'undefined'". Which seems to be because of the fact that finds can possibly not find something but in my example you're only allowed to look for "one" or "two" which would always return a result.
How do I get typescript to know it will always return a result in the find?
findmight not succeed in finding anything in which case.datawill not be valid. If you assign the result to a typed variable then it should probably assume it's always validfind()returns a possibly-null result. But if you're sure that it can't be null you can assert that via the non-null assertion operator...namedItems.find(predicate)!.data