【问题标题】:Object destructuring with interface带接口的对象解构
【发布时间】:2021-08-09 18:26:47
【问题描述】:

菜鸟问题,但我正在尝试通过以下方式解构对象

interface ICount {
    one: string,
    two: string
}

const count = {
    one: "test",
    two: "hey",
    three: "morning"
}

const test: ICount = count;

console.log(test);

我希望 测试

{
    one: "test",
    two: "hey"
}

但它也分配了三个。我做错了什么?

【问题讨论】:

  • 你只是类型提示 test 将包含一个具有onetwo 属性的对象,它就是这样做的。您不会破坏任何东西,也不会限制 test 可以容纳的内容,只要它确实容纳了界面指示的内容。

标签: javascript typescript object


【解决方案1】:

您只是将测试对象键入为 ICount 类型,您没有更改任何值。

如果你想解构这三个值,你可以像这样使用简单的 javascript 解构

const { three, ...rest } = count

console.log(rest) // { one: "test", two: "hey" }

【讨论】:

    猜你喜欢
    • 2020-12-16
    • 2020-10-30
    • 2023-03-07
    • 2011-11-03
    • 2019-12-12
    • 1970-01-01
    • 2016-02-17
    • 2013-01-24
    • 1970-01-01
    相关资源
    最近更新 更多