简体   繁体   中英

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.

How can I delcare object literal type in sucha way without errorprone casing via as Foo ?

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

    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

Ok, I have found the answer that satisfies me. Specify generic return type of map , but that applies to generics only. I would still want something more like {name:bar}:Foo

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM