简体   繁体   English

Typescript — 定义“空对象”类型

[英]Typescript — Define “Empty object” type

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

I've typed the same examples but for "d" and "e" I don't get any error inside my.ts file... Are those 2 missing errors linked to some TS config?我输入了相同的示例,但对于“d”和“e”,我在 my.ts 文件中没有收到任何错误...这两个缺失的错误是否与某些 TS 配置相关联?

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

Typescript has a --strictNullChecks flag: Typescript 有一个--strictNullChecks标志:

In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).在严格的 null 检查模式下,null 和 undefined 值不在每种类型的域中,并且只能分配给它们自己和任何类型(一个例外是 undefined 也可以分配给 void)。

You seem to not have this enabled, which means that null and undefined can be of any type.您似乎没有启用此功能,这意味着 null 和 undefined 可以是任何类型。 Since this is the sensible option, along with various other strict flags, typescript has a --strict flag that enables --strictNullChecks and the other flags.由于这是明智的选择,连同其他各种严格标志,typescript 有一个--strict标志,可以启用--strictNullChecks和其他标志。

Read more about compiler options here. 在此处阅读有关编译器选项的更多信息。

This flag is also visible in the "TS Config" section of the typescript playground :此标志在typescript 游乐场的“TS Config”部分中也可见: 在此处输入图像描述

This is not the best solution, because you should wrap it into func.这不是最好的解决方案,因为您应该将它包装到 func.xml 中。 DOn't know if it works for You.不知道它是否适合你。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM