Reputation: 282895
Example:
function parseInt<TDefault>(nbr: string, defaultValue:TDefault = null):number|TDefault {
return Math.random() || defaultValue
}
Type 'null' is not assignable to type 'TDefault'. 'TDefault' could be instantiated with an arbitrary type which could be unrelated to 'null'.(2322)
This errors because null
isn't necessarily of type TDefault
, which makes sense, but I don't want to make the types looser because then my return value will have to include |null
, but if you supply a default, then it's guaranteed to never be null
.
So how can I get this to work?
Upvotes: 2
Views: 198
Reputation: 282895
You can use method overrides:
export function parseInt<TDefault>(nbr: string, defaultValue: TDefault): number | TDefault
export function parseInt(nbr: string): number | null
export function parseInt(nbr: string, defaultValue: any = null) {
return Math.random() || defaultValue
}
const x = parseInt("5.0")
const y = parseInt("bacon", {wat:9})
Upvotes: 1