【问题标题】:Typed default arguments in destructuring parameters在解构参数中键入默认参数
【发布时间】:2017-02-20 09:29:11
【问题描述】:

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

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

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

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 的语法?

【问题讨论】:

    标签: typescript types typescript2.0


    【解决方案1】:
    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';
    }
    

    使用默认参数时,您的目标是类型推断。如果没有类型定义或者您想提供自己的类型定义,只需使用“变量作为类型”语法进行转换! :)

    【讨论】:

    • 有趣。我没有考虑过类型强制扩展类型的能力 - 通常我已经看到它用于缩小类型。此外,还有一个相关问题是解构参数不能包含任何没有默认值(必需或可选)的类型化参数 - 至少没有像 example3 中的显式类型。
    猜你喜欢
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2017-07-12
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多