简体   繁体   English

如何在 Typescript 中删除所需的 Object 文字类型

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

Lets consider simple code让我们考虑简单的代码

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;
})

In case of short lambdas I would like to omit assignment of the variable and yet let compiler to know what type object literal should be so error will be shown.在短 lambda 的情况下,我想省略变量的分配,但让编译器知道 object 文字应该是什么类型,因此将显示错误。

How can I delcare object literal type in sucha way without errorprone casing via as Foo ?我怎样才能通过as Foo以这种方式 delcare object 文字类型而不容易出错?

Since I was accused of beeing inaccurate, using bad examples and invalid use of map, arrays (which is simply irrelevant in this example bad code) here is something which I hope is more verbose由于我被指控不准确,使用不良示例和无效使用 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);
   } 

Here is a playground 这里是游乐场

I would gladly see a syntax like {name:bar}:Foo to denote that literal must mach Foo instead of force casting is with as我很乐意看到像{name:bar}:Foo这样的语法来表示文字必须 mach Foo而不是强制转换是 with as

Ok, I have found the answer that satisfies me.好的,我找到了令我满意的答案。 Specify generic return type of map , but that applies to generics only.指定map的通用返回类型,但这仅适用于 generics。 I would still want something more like {name:bar}:Foo我仍然想要更像{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