基于这篇文章https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492
我输入了相同的示例,但对于"d“和"e”,我在.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发布于 2020-12-06 15:55:49
类型记录有一个--strictNullChecks标志:
在严格的空检查模式中,空值和未定义值不在每种类型的域中,只能分配给自己和任何类型(唯一的例外是未定义的值也可分配为无效)。
您似乎没有启用此功能,这意味着空值和未定义的值可以是任何类型。由于这是明智的选择,加上各种其他严格标志,类型记录有一个--strict标志,可以启用--strictNullChecks和其他标志。
此标志在打字稿操场的"TS Config“部分也是可见的:

发布于 2020-12-06 15:51:13
这不是最好的解决方案,因为您应该将它封装到func中。不知道这对你有用吗。
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 expectedhttps://stackoverflow.com/questions/65169583
复制相似问题