【问题标题】:destruct object with interface使用接口破坏对象
【发布时间】:2018-09-15 14:55:35
【问题描述】:

我有这个代码:

const {items} = this.props;

但是,我需要将接口设置成items常量

我不想这样做:

const items: ItemsInterface = this.props.items

可能吗?

【问题讨论】:

  • 你试过让你的组件扩展React.Component<{items: ItemsInterface, ..}>吗?这应该可以推断出this.props.items 的正确类型。

标签: javascript reactjs typescript javascript-objects object-destructuring


【解决方案1】:

正如 Oblosys 在他的评论中所说,首选方法应该是解构类型良好的源对象并依赖类型推断。

类型注释语法与解构语法的交互笨拙且不便。

不过,如果您真的希望在解构表达式中赋予类型,有几种方法。

  1. 最简单的方法是在表达式的右侧应用类型断言

    const {items} = <{items: ItemsInterface}>this.props;
    

    或者等价

    const {items} = this.props as {items: ItemsInterface};
    

    当然这是冗长的,但它是清晰、正确和明显的。

  2. 也许更接近您的直觉,您可以像使用其他任何方法一样使用类型注释指定解构表达式的类型。

    const {items}: {items: ItemsInterface} = this.props;
    

    我个人觉得这很尴尬,而且有点难以阅读。类型注释归属于未命名的表达式{items}

  3. 如果您顺便在解构表达式中指定了默认值,则实际上可以内联指定类型。

    const {items = <ItemsInterface>{}} = this.props;
    

或者等价

    const {items = {} as ItemsInterface} = this.props;

无论如何,除非您使用默认值进行初始化,否则无法避免重复名称 items

我更喜欢第一个选项,因为更改现有值的类型(此处为this.props)对该值应用 断言 比添加类型 注解更简洁 到接收声明,这里是items,因为后者没有让读者直观地知道类型是手动调整的。

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多