简体   繁体   中英

Typescript — Define “Empty object” type

Based on this post 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?

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:

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).

You seem to not have this enabled, which means that null and undefined can be of any type. Since this is the sensible option, along with various other strict flags, typescript has a --strict flag that enables --strictNullChecks and the other flags.

Read more about compiler options here.

This flag is also visible in the "TS Config" section of the typescript playground : 在此处输入图像描述

This is not the best solution, because you should wrap it into func. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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