【问题标题】:How to assign types to destructured variables in Typescript? [duplicate]如何为 Typescript 中的解构变量分配类型? [复制]
【发布时间】:2019-08-08 05:01:29
【问题描述】:

如果我想为传递给函数的每个解构参数分配不同的类型,而不是统一类型,格式应该是什么?

例如,如果我希望所有三个变量都是字符串,则格式如下:

const Auth = ({ history, match, path }: string) => {
    //content
}

但是,如果我希望第一个是对象,第二个是字符串,第三个是数组呢?

【问题讨论】:

  • mariusschulz.com/blog/…。搜索您的确切标题将其作为第一个结果。有时(几乎总是)搜索会更快。

标签: javascript reactjs typescript typescript-typings


【解决方案1】:

您必须完全键入要解构的对象。

const Auth = ({ history, match, path }: {
  history: string,
  match: string,
  path: string
}) => {
    //content
}

Typescript 然后会查找这些属性的类型,然后正确推断出正确的类型。


一些变化。

为被解构的对象创建一个离散类型。 (我在 react props 中经常使用这种模式):

interface AuthInfo {
  history: string,
  match: string,
  path: string
}

const Auth = ({ history, match, path }: AuthInfo) => {
    //content
}

或弱类型:

const Auth = ({ history, match, path }: { [key: string]: string }) => {
    //content
}

不同key的不同类型:

const Foo = ({ a, b }: { a: string, b: number[] }) => {
    //content
}

【讨论】:

    【解决方案2】:

    您需要声明整个对象的类型作为参数传递给Auth,即

    const Auth = ({ match, path }: {match: string, path: string[]}) => {
    }
    

    : 右边的所有内容都是参数的类型。不幸的是,这可能会变得非常冗长和重复。

    请注意,您也必须在初始代码中执行此操作 - 您的示例函数接受 字符串类型的单个参数 并尝试对其进行解构。这不会编译,字符串没有名为 pathhistory 的属性(它确实有一个名为 match 的方法,因此可以工作,但可能不是您想要的)

    【讨论】:

      【解决方案3】:

      在打字稿中,最好使用以下语法:

      const Auth = ({ history:object, match:string, path :string}) =>
        { // function contents
        }
      

      【讨论】:

      • 这并不像你想象的那样。这是重命名的对象解构;它被 TS 编译器原封不动地通过。在我评论的链接中也进行了讨论,但这只是标准的 ES6 语法。
      猜你喜欢
      • 2018-08-22
      • 2023-02-26
      • 2020-03-08
      • 2019-05-04
      • 2018-08-16
      • 1970-01-01
      • 2021-07-13
      • 2016-11-28
      • 2020-05-22
      相关资源
      最近更新 更多