Reputation: 21814
I want a function to return either an object or null.
Here is how I handle it today:
export interface MyObject {
id: string
}
function test(id) : MyObject | null {
if (!id) {
return null;
}
return {
id: id
}
}
Is this best practice?
I would prefer to make the interface nullable rather than returning MyObject | null
.
But I don't know if that is possible.
Upvotes: 2
Views: 3157
Reputation: 23762
Is this best practice?
It's just fine. Everybody does that (or with undefined
).
I would prefer to make the interface nullable rather than returning
MyObject | null
.
You can do:
export type NullableObject = null | {
id: string
}
It is uncommon but fine too.
Upvotes: 2
Reputation: 10884
In Typescript, null and undefined are part of the domains of all types, unless strict null checks are enabled. In my opinion, explicitly declaring nulls is a much better practice than having them everywhere implicitly, but in the real world it is often not realistic to enable strict mode when interoperating with library code that isn't designed for it.
Upvotes: 1
Reputation: 92677
This should handle null case too (if --strictFunctionTypes compiler option is off)
function test(id) : MyObject {
if (!id) {
return null;
}
return {
id: id
}
}
Upvotes: 0