Let's analyze a straightforward code snippet
interface Foo{
bar:string;
idx:number;
}
const test1:Foo={bar:'name'}; // this is highly recommended as it includes all required fields
const test2={bar:'name'} as Foo; // this is not the ideal approach
[1,2,3].map(i=>(
{
idx:i //this is clearly incorrect as 'bar' value is missing, should be caught by the compiler
} as Foo)
);
[1,2,3].map(i=>{
const foo:Foo={ //This is an optimal method but I prefer avoiding unnecessary assignments.
idx:i
};
return foo;
})
For short lambdas, it would be convenient to skip assigning variables while still informing the compiler about the type of object literal to display any errors.
How can object literal type be declared without using as Foo
and maintaining precision?
I have provided a more detailed example since accusations were made regarding inaccuracies and improper use of map and arrays (irrelevant in this context).
interface Foo {
bar:string;
idx:number;
}
const arr:any[]=[]; // declaring it as Foo[] wouldn't be appropriate.
//definitely not a foo! Compiler check for a match with foo
[1,2,3].forEach(i=>arr.push({idx:i} as Foo));;
//the current method works, but how can we achieve it without assignment?
[1,2,3].forEach(i=>{
const foo:Foo={idx:i};// compiler will detect the error
arr.push(foo);
}
It would be beneficial to have a syntax like {name:bar}:Foo
to signify that a literal must meet the requirements of Foo
instead of resorting to using as