bjnsn - 1 year ago 101

TypeScript Question

One of my favorite features of es6 is the ability to use destructuring parameters.

For example:

`function example1({`

bar = -1,

transform = Math.abs

} = {}) {

transform(bar);

}

However, the typescript compiler generates

`type Formatter = { (n: number): (number | string) };`

function example2({

bar = -1,

transform: Formatter = Math.abs

} = {}) {

// ERROR: cannot find name 'transform'

return transform(bar) + ' is the value';

}

The only way around this I've found is to explicitly type the whole set of parameters - which seems overly complex when the remaining parameter types can be inferred:

`type Formatter = { (n: number): (number | string) };`

type ExampleOpts = {

bar?: number,

transform?: Formatter

};

function example3({

bar = -1,

transform= Math.abs

}: ExampleOpts = {}) {

return transform(bar) + ' is the value';

}

Thoughts? Is there are syntax that accomplishes #3 with the simplicity of #2 that I'm missing?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
type Formatter = { (n: number): (number | string) };
function example2({
bar = -1,
transform = Math.abs as Formatter
} = {}) {
// ERROR: cannot find name 'transform'
return transform(bar) + ' is the value';
}
```

When using default parameters, you are aiming for type inference. If there's no type definition or you'd like to provide your own, simply cast it with the 'variable as type' syntax! :)

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**