To specify that the variable ret
will represent a Foo
element, you can use the keyword as
enum Field {
age,
bugs,
}
interface Foo {
number_age: number;
number_bugs: number;
}
function makeFoo():Foo {
let ret = {} as Foo;
let i = 0;
for (let key in Field) {
ret['number_'+key] = i++;
}
return ret;
}
Refer to the documentation on type assertions:
There may be instances where you have more knowledge about a value than TypeScript. This can occur when you know the specific type of an entity.
Type assertions allow you to inform the compiler that you are aware and confident about the type of a value. Unlike type casts in other languages, type assertions do not perform any data restructuring or runtime actions. They are solely used by the compiler. TypeScript assumes that as a programmer, you have conducted any necessary validations.
Type assertions can take two forms. One is the “angle-bracket” syntax:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
The other form is the as-syntax:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Both examples are functionally equivalent. The choice between them is typically based on personal preference. However, when working with TypeScript and JSX, only as-style assertions are permitted.