I have a project using typescript 3.7.2 and every time i use the "find" method on arrays vs code does not show "undefined" as a possible return type.
interface Repository<T, TID> {
get: (id: TID) => T | undefined;
}
class CustomerRepository implements Repository<Customer, string> {
private customers: Customer[];
constructor() {
this.customers = [
{
id: "ID1",
name: "Generic Customer 1",
age: 30
},
{
id: "ID2",
name: "Generic Customer 2",
age: 40
},
{
id: "ID3",
name: "Generic Customer 3",
age: 50
}
]
}
get(id: string): Customer | undefined {
return this.customers.find(customer => customer.id === id);
}
}
It does not matter if i call the "get" method on the repository or call "this.customers.find" inside the repository, it still won't show "undefined" as a possible return type. This code will compile and then chrash immediately after running:
const customer = customerRepo.get("ID4");
console.log(customer.id);
This is my tsconfig.json file:
{
"compilerOptions": {
"target": "es5",
"module": "es6",
"allowJs": true,
"sourceMap": true,
"outDir": "./dist",
"lib": ["dom", "es6", "dom.iterable", "scripthost"],
"noImplicitAny": true
},
"exclude": [
"./node_modules/**/*",
"definitions"
]
}
undefined and null are absorbed by other types in unions unless the strictNullChecks option is specified in tsconfig. See docs for all options.
If you add the option undefined will be present in the return type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With