[英]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.