首页 > 解决方案 > 如何在打字稿中获得严格的值类型?

问题描述

例如,我有一个函数签名如下:

declare function foo<T>(input: T): T;

我希望它返回严格类型的输入对象而不手动设置模板类型:

const bar = foo({ str: 'foo', bool: true })

的预期类型bar是:{ str: 'foo', bool: true }

而不是{ str: string; bool: boolean }.

标签: typescript

解决方案


从 TypeScript 3.4 开始,编写

const bar = foo({ str: 'foo', bool: true } as const)

推荐阅读