【问题标题】:Typescript type casting when destructuring [duplicate]解构时的打字稿类型转换[重复]
【发布时间】:2017-04-10 17:44:30
【问题描述】:

让我们假设这个

{foo, bar} = groupBy(arg);

我想将 foo 转换为 Foo 并将 bar 转换为 Bar。我该怎么做?

我是 Typescript 的初学者。 groupBy 来自 lodash 包。

【问题讨论】:

    标签: typescript lodash


    【解决方案1】:

    如果 Typescript 无法推断出 groupBy 的结果类型,你可以尝试自己断言。

    function groupBy(o: any) {
        return o; // return any
    }
    
    let x = { a: 1, b: "1" }
    
    // we know better than tsc and assert the type
    let {a, b} = <{ a: number, b: string }>groupBy(x);
    

    【讨论】:

    • 其实这正是我想要的!谢谢!
    • 您还应该检查来自 artem 的副本,它有一个更清洁的解决方案。
    • 这并不总是有效,因为更复杂的对象会导致 TS2352(类型重叠不足)。即const {target} = &lt;{target: HTMLInputElement}&gt;mouseEvent.
    猜你喜欢
    • 1970-01-01
    • 2017-08-04
    • 2018-12-17
    • 2017-08-12
    • 2022-01-04
    • 1970-01-01
    • 2018-08-12
    • 2022-01-21
    • 2021-06-24
    相关资源
    最近更新 更多