簡體   English   中英

如何在 Typescript 中刪除所需的 Object 文字類型

[英]How to delare required type of Object literal in the Typescript

讓我們考慮簡單的代碼

interface Foo{
  bar:string;
  idx:number;
}


const test1:Foo={bar:'name'}; // this is very good - missing non optional field
const test2={bar:'name'} as Foo; // this is bad

[1,2,3].map(i=>(
  {
      idx:i //this is obviously invalid as name is missing, compiler should catch it
  } as Foo)
);

[1,2,3].map(i=>{
  const foo:Foo={ //This is very good but I would like to ommit assignment. 
      idx:i
  };
  return foo;
})

在短 lambda 的情況下,我想省略變量的分配,但讓編譯器知道 object 文字應該是什么類型,因此將顯示錯誤。

我怎樣才能通過as Foo以這種方式 delcare object 文字類型而不容易出錯?

由於我被指控不准確,使用不良示例和無效使用 map、arrays(在此示例中與錯誤代碼無關)這是我希望更詳細的內容

    interface Foo {
        bar:string;
        idx:number;
    }
      const arr:any[]=[]; // no I cannot declare it as Foo[], this would be too obvious. 
    
//this is not a foo! force compiler to check if it matches foo
      [1,2,3].forEach(i=>arr.push({idx:i} as Foo));; 



//this works, but how to do it without assignment
      [1,2,3].forEach(i=>{
        const foo:Foo={idx:i};// compiler correctly complains
        arr.push(foo);
   } 

這里是游樂場

我很樂意看到像{name:bar}:Foo這樣的語法來表示文字必須 mach Foo而不是強制轉換是 with as

好的,我找到了令我滿意的答案。 指定map的通用返回類型,但這僅適用於 generics。 我仍然想要更像{name:bar}:Foo

[1,2,3].map<Foo>(i=>(
  {
      idx:i //now this works
  })
);

暫無
暫無

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

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