解构时打字稿类型转换

Alk*_*ris 11 typescript lodash

让我们假设这个

{foo, bar} = groupBy(arg);
Run Code Online (Sandbox Code Playgroud)

我想将 foo 转换为 type Foo,将 bar 转换为 type Bar。我怎样才能做到这一点?

我是一个完整的 Typescript 初学者。groupBy是 lodash 包中的一个。

tos*_*skv 19

如果 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);
Run Code Online (Sandbox Code Playgroud)

  • 这并不总是有效,因为更复杂的对象会导致 TS2352(类型重叠不足)。即 `const {target} = &lt;{target: HTMLInputElement}&gt;mouseEvent`。 (5认同)