簡體   English   中英

如何在打字稿中創建復雜對象

[英]How to create a complex object in typescript

我需要創建一個復雜的對象,它的值需要從另一個對象計算或復制。

我需要創建的對象

interface A extends B {
key1: string
key2: {
is's a complex object with many keys
}
}

我使用這些代碼

const a: A = Object.assign({}, b); //ts error here
a.key1 = around 10 lines of calc
a.key2 = around 10 lines of calc

但出現錯誤TS2741: Property 'key1, key2' is missing in type 'a' but required in type 'A'.

有沒有辦法在多行中創建一個對象而無需編寫像Object.assign({}, b, {key1: 10line, key2: 10line})這樣的不可讀代碼?

這是我分配復雜變量的一種方式。 我沒有使用接口來幫助理解。

   let myObject: { key: { subkey: string } } = {key: {subkey: ""}};

    myObject = {
      ...myObject,
      key: { subkey: "value" }
    };

如果你可以使用最新的標准,你可以使用對象析構,它基本上是 Object.assign() 的一個糖。 語法使用三個點“...”

const a: A = {...b, key1: /*Complex calc*/, key2: /*Complex calc*/};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM