简体   繁体   中英

TS: How do I type an arrow function with a parameter that has a default value?

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

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'"?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM