Set a default value for a generic type parameter

Viewed 229

I want to make a generic function that takes a literal string parameter and returns a value depending on the passed parameter. But this parameter should be optional, and if it was not passed, then I need to set the default value.

type Foobar = 'a' | 'b' | 'c' | 'd' | 'e' | 'f'

function f1<T extends Foobar = 'a'>(param: T = 'a') {}

function f2<T extends Foobar>(param: T = 'a') {}

function f3<T>(param: T = 'a') {}

How do I set a default value for the param if all the examples above don't work?

1 Answers

Try this instead. You don't need the generics based on what you're asking. You already have a type defined that you can use as the parameter type.

function f3(param: Foobar = 'a') {}

Related