如何在 TypeScript 中指定类型化对象文字? [英] How can I specify a typed object literal in TypeScript?

查看:30
本文介绍了如何在 TypeScript 中指定类型化对象文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法直接创建一个类型化的对象字面量?

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;
}

我也可以这样做:

function testB(): BaseInfo = {
   return { value: 1, name: 'Hey!' };
}

但我需要的是:

function testC(): BaseInfo = {
   return { value: 1, name: 'Hey!' }: MyInfo; // <--- doesn't work
}

或者像这样:

function testD(): BaseInfo = {
   return MyInfo: { value: 1, name: 'Hey!' }; // <--- doesn't work
}

推荐答案

答案是使用恒等函数:

function to<T>(value: T): T { return value; }
const instance = to<MyInfo>({
    value: 1,
    name: 'Hey!',
});

to 函数将被 JIT 编译器优化掉,因此调用函数不会影响性能

the to function is going to be optimized away by the JIT compiler, so there is no performance impact of calling a function

这篇关于如何在 TypeScript 中指定类型化对象文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆