[英]Typescript — Define “Empty object” type
基于这篇文章https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492
我输入了相同的示例,但对于“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 有一个--strictNullChecks
标志:
在严格的 null 检查模式下,null 和 undefined 值不在每种类型的域中,并且只能分配给它们自己和任何类型(一个例外是 undefined 也可以分配给 void)。
您似乎没有启用此功能,这意味着 null 和 undefined 可以是任何类型。 由于这是明智的选择,连同其他各种严格标志,typescript 有一个--strict
标志,可以启用--strictNullChecks
和其他标志。
此标志在typescript 游乐场的“TS Config”部分中也可见:
这不是最好的解决方案,因为您应该将它包装到 func.xml 中。 不知道它是否适合你。
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.