【发布时间】: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