解构参数中的类型化默认参数

Typed default arguments in destructuring parameters

我最喜欢的 es6 功能之一是能够使用解构参数。 例如:

function example1({
    bar = -1,
    transform = Math.abs
} = {}) {
    transform(bar);
}

但是,当需要将显式类型分配给其中一个参数时,打字稿编译器会生成错误(例如,使其具有比默认推断更大的灵活性) ):

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';
}

我发现解决这个问题的唯一方法是显式键入整组参数 - 当可以推断其余参数类型时,这似乎过于复杂:

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';
}

想法?是否有语法可以用我所缺少的#2 的简单性来完成#3?

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';
}

使用默认参数时,您的目标是进行类型推断。如果没有类型定义或者您想提供自己的类型定义,只需使用 'variable as type' 语法进行转换即可! :)