1

How do I type an arrow function with a parameter that has a default value? before in javascript, it is a function that accepts a boolean value and when it is not provided it defaults to false

const foo = (initial = false) => 

now I rewrote this function into TS and expand the param to be able to get a function that returns a boolean,

const foo = <T extends boolean>(initial: T | (() => T)) =>

Now the problem is that I still need to make initial default to false when it is not provided. How can I do that in TS? I tried a few but it doesn't pass the TS compiler.

For example

const foo = <T extends boolean>(initial = false: T | (() => T)) =>

will be a syntax error in TS

Joji
  • 4,703
  • 7
  • 41
  • 86
  • 3
    Is there a reason you are using Generics here, why not Boolean. Also, What value would you want to return when a non boolean value is used? – Tushar Shahi Jul 19 '21 at 18:38
  • You need to specify the default value after the type: `initial: T | (() => T) = false` – Krisztián Balla Jul 19 '21 at 18:43
  • 2
    @KrisztiánBalla this might not work. false can't be a value for all types of `T`. Using Generics is a problem here. – Tushar Shahi Jul 19 '21 at 18:47
  • Generics and default values don't play well together, as others have said, because you cannot know that `false` is assignable to `T`. Why not `const foo = (initial: boolean | (() => boolean) = false) =>` as in [this](https://tsplay.dev/WPjxLN)? If you really need generics, please consider modifying your question to include a [mcve] that gives clear criteria for accepting/rejecting an answer. For example, it would be helpful if you would provide an implementation and/or return type annotation for `foo` that uses `T` in a plausible way. – jcalz Jul 19 '21 at 19:22
  • Does this answer your question? [How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"?](https://stackoverflow.com/questions/56505560/how-to-fix-ts2322-could-be-instantiated-with-a-different-subtype-of-constraint) – AncientSwordRage Jan 11 '23 at 17:36

2 Answers2

1

There's no obvious need for this to be a generic function. So let's make your life a lot easier.

The syntax you want is:

argName: ArgType = defaultValue

Or in your case:

initial: boolean | (() => boolean) = false

Full example:

const foo = (initial: boolean | (() => boolean) = false) => () => initial
console.log(foo()()) // false
console.log(foo(true)()) // true

Playground

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
0

You cannot assing a concrete value to a generic , In typescript, a concrete instance is not allowed to be assigned to a type parameter.

Refer to this answer for detail

How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"?

Goutham J.M
  • 1,726
  • 12
  • 25