解包对象时定义属性的类型

问题描述 投票:0回答:2

我将一个对象解压缩为几个变量,并且我想定义一个属性的类型,该属性将从一个对象解压缩其余的属性。

例如:

interface FooBar { name: string }

const {a, b, ...c} = d;

我需要将c的类型声明为FooBar

我已经尝试过预先声明变量:

let c: FooBar;
let {a, b, ...c} = d;

也尝试过类型语法:

let {a, b, ...c:FooBar} = d;

我尝试将d强制转换为该类型,但会收到ab不属于该类型的错误。

let {a, b, ...c} = d as FooBar;

我尝试了自定义类型,但收到错误:

let {a, b, ...c} = d as {a:any, b:any, c:FooBar};

使用TypeScript解压缩对象时,是否可以定义类型?

已更新:

这里是一个更好的编码示例,解释了涉及的不同类型:

interface FooBar {
   name: string
}

interface Other {
   a: number;
   b: number;
   name: string;
}

function convert(d: Other) {
   const {a, b, ...c} = d;
   c.name;
   // ^^^ -- WebStorm does not match "name" as a property of FooBar.
   //        It matches to ALL interfaces that have any property called "name". 
}

上面的问题是我不能重构接口FooBar,因为WebStorm在实现该接口时未明确匹配c。它将其视为具有name属性的匹配all类型。

所以我想将c定义为FooBar类型。

javascript typescript
2个回答
0
投票

希望我能正确理解您,希望能对您有所帮助。

    const d = {
      a: {
        name: 'a'
      },
      b: {
        name: 'b'
      },
      c: {
        name: 'c'
      }
    }

    type FooBar = { name: string }
    interface Baz {[key:string]: FooBar}

    const {a, b, ...c}: Baz = d;

0
投票

对象中的解构分配的工作原理是这样的>>

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.