Considering enabling the strictNullChecks
flag for a TypeScript project I've been developing leads to numerous compiler errors. While some of these errors are relevant edge cases, many follow a specific pattern.
type BusinessObject = {
id: string;
name: string;
requiredValue: number;
// ...
}
class DataStore {
// ...
public addItem(item: BusinessObject): Promise<string>;
public getItem(id: string): Promise<BusinessObject>;
}
function consumeData(store: DataStore){
store.addItem({name:"one", requiredValue:1});
store.getItem("two").then(item => console.log(item.id));
}
The issue arises with the 'id' property, generated by the database and therefore only "optional" when creating a new item. If I make the 'id' property mandatory (no '?'), I encounter a compiler error in the 'addItem' call. However, if I make the ID property optional, every reference to it must include a guard or non-null assertion operator (item.id!
).
One workaround I've thought of is casting the argument passed to 'addItem' as any
, but this disables checking on other properties of 'BusinessObject', making it an imperfect solution. A potential solution I'm looking for is akin to the non-null assertion operator, allowing me to assert that a null assignment is acceptable despite the type declaration suggesting otherwise, like so:
store.addItem({id: undefined!, name:"one", requiredValue:1});
.
I am open to better/more consistent ways of describing this issue and its resolution.