bjnsn bjnsn - 1 month ago 17
TypeScript Question

Typed default arguments in destructuring parameters

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 an error when an explicit type needs to be assigned to one of the arguments (e.g. to give it greater flexibility than would be inferred by the default):

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?

Answer
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! :)

Comments