Issue
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
}
Solution
Answer is to use the identity function:
function to<T>(value: T): T { return value; }
const instance = to<MyInfo>({
value: 1,
name: 'Hey!',
});
there should be no performance impact for an unnecessary call the to
function, it should be optimized away by the JIT compiler
Answered By - Trident D'Gao
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.