首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型--定义“空对象”类型

类型--定义“空对象”类型
EN

Stack Overflow用户
提问于 2020-12-06 15:10:46
回答 2查看 949关注 0票数 1

基于这篇文章https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492

我输入了相同的示例,但对于"d“和"e”,我在.ts文件中没有任何错误.这两个缺失的错误是否与某些TS配置相关联?

代码语言:javascript
复制
export type EmptyObject = Record<string, never>

const a: EmptyObject = { a: 1 }    // I get error - as expected
const b: EmptyObject = 1           // I get error - as expected
const c: EmptyObject = () => {}    // I get error - as expected

const d: EmptyObject = null        // NO ERROR, but it SHOULD show ERROR message
const e: EmptyObject = undefined   // NO ERROR, but it SHOULD show ERROR message

const f: EmptyObject = {} // I get NO ERROR - as expected
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-06 15:55:49

类型记录有一个--strictNullChecks标志:

在严格的空检查模式中,空值和未定义值不在每种类型的域中,只能分配给自己和任何类型(唯一的例外是未定义的值也可分配为无效)。

您似乎没有启用此功能,这意味着空值和未定义的值可以是任何类型。由于这是明智的选择,加上各种其他严格标志,类型记录有一个--strict标志,可以启用--strictNullChecks和其他标志。

在这里阅读有关编译器选项的更多信息。

此标志在打字稿操场的"TS Config“部分也是可见的:

票数 1
EN

Stack Overflow用户

发布于 2020-12-06 15:51:13

这不是最好的解决方案,因为您应该将它封装到func中。不知道这对你有用吗。

代码语言:javascript
复制
type Keys<T> = keyof T
type Values<T> = T[keyof T]
type Empty = {} & { __tag: 'empty' };

type IsEmpty<T> =
  Keys<T> extends never
  ? Values<T> extends never
  ? Empty : never
  : never

const empty = <T extends Record<string, never>>(arg: T) => arg as IsEmpty<T> extends Empty ? T : never

const a: Empty = empty({ a: 1 })    // I get error - as expected
const b: Empty = empty(1)           // I get error - as expected
const c: EmptyObject = empty(() => { })    // I get error - as expected

const d: Empty = empty(null)        //  ERROR, but it SHOULD show ERROR message
const e: Empty = empty(undefined)   //  ERROR, but it SHOULD show ERROR message

const f: Empty = ({}) // NO ERROR - as expected
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65169583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档