Is there a way to make a typed object literal directly?
By directly I mean without having to assign it to a variable which is type annotated.
For example, I know I can do it like this:
export interface BaseInfo { value: number; } export interface MyInfo extends BaseInfo { name: string; } function testA(): BaseInfo = { const result: MyInfo = { value: 1, name: 'Hey!' }; return result; }
I also can do it like this:
function testB(): BaseInfo = { return { value: 1, name: 'Hey!' }; }
But what I need is something like:
function testC(): BaseInfo = { return { value: 1, name: 'Hey!' }: MyInfo; // <--- doesn't work }
Or like this:
function testD(): BaseInfo = { return MyInfo: { value: 1, name: 'Hey!' }; // <--- doesn't work }
To define an object of objects type in TypeScript, we can use index signatures with the type set to the type for the value object. const data: { [name: string]: DataModel } = { //... }; to create a data variable of type { [name: string]: DataModel } where DataModel is an object type.
The object literal is a short form of creating an object. Define an object in the { } brackets with key:value pairs separated by a comma. The key would be the name of the property and the value will be a literal value or a function.
The process of changing types is what is called “type casting”. Typecasting in strongly typed languages like C# allow us to convert types. string numStr = "123"; int numNum; bool isParsable = Int32. TryParse(numStr, out numNum);
The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.
Intellisense for members of object literals is provided by the contextual type (see section 4.19 of the spec) of the expression.
You can acquire a contextual type in a variety of ways. Some of the most common places where a contextual type is applied are:
return
statement in a function or getter with a return type annotation<T>expr
)In your example, you can use a type assertion to force your object literal to have a contextual type:
function testB() { return <IMyInfo>{ name: 'Hey!' }; }
Answer is to use the identity function:
function to<T>(value: T): T { return value; } const instance = to<MyInfo>({ value: 1, name: 'Hey!', });
the to
function is going to be optimized away by the JIT compiler, so there is no performance impact of calling a function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With