mpen
mpen

Reputation: 282895

How to set a default return value of an arbitrary type?

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)

TypeScript Playground

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

Answers (1)

mpen
mpen

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})

playground

Upvotes: 1

Related Questions