【问题标题】:Babel 7 + Typescript Unexpected token when using destructuring in function methodBabel 7 + Typescript 在函数方法中使用解构时出现意外标记
【发布时间】:2018-10-31 12:18:25
【问题描述】:

我收到以下错误:

SyntaxError: /Path/to/File.tsx: Unexpected token, expected ";" (73:76)

为:

interface Foo {
   bar: ({name: string, age: number}) => void;
}

这不会:

interface Bar {
   name: string;
   age: number;
}

interface Foo {
   bar: (props: Bar) => void;
}

.babelrc

{
    "presets": [
        "@babel/env",
        "@babel/typescript",
        "@babel/react"
    ],
    "plugins": [
        "@babel/proposal-class-properties",
        "@babel/proposal-object-rest-spread",
        "@babel/transform-arrow-functions"
    ]
}

我还需要什么其他插件?

【问题讨论】:

  • 我没有看到任何传播。你的意思是解构吗?错误究竟在哪里?两个代码sn-ps有什么关系?
  • @FelixKling 对,对不起,我的意思是destructuring。我发布了从终端收到的错误。我想使用第一个示例,而不是第二个示例。

标签: javascript typescript babeljs


【解决方案1】:

我无法在操场上重现错误(但我猜它不使用 Babel)。但是,来自Typescript docs

属性重命名

您还可以为属性指定不同的名称:

let { a: newName1, b: newName2 } = o;

这里的语法开始变得混乱。您可以将a: newName1 读作“a as newName1”。方向是从左到右,就像你写的那样:

let newName1 = o.a;
let newName2 = o.b;

令人困惑的是,这里的冒号并不表示类型。类型,如果指定的话,还是需要在整个解构之后写:

let { a, b }: { a: string, b: number } = o;

所以你必须将方法定义为

interface Foo {
  bar: ({name, age}: {name: string, age: number}) => void;
}

【讨论】:

    猜你喜欢
    • 2019-09-02
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 2023-01-13
    • 2020-11-02
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    相关资源
    最近更新 更多