简体   繁体   中英

Why does `keyof object` return a never type?

Why does keyof object return a never type?

I think the right thing should be number | string | symbol number | string | symbol

type T = keyof object // never

The type object does not have any keys in it. Therefore you don't receive the union you expect but simply the type never instead.

The object type almost represents the same thing as {} . The difference ist that object only accepts non-primitives while {} accepts anything that isn't null or undefined . (Thanks to @jcalz in the comments). Looking at {} it seems very obvious that there are no keys on the type. Since there are no keys to map TypeScript simply returns the type never .

Note that {} is a type in your case and not a value. You cannot/don't have to do something like

type T = typeof {};
             // ~ --> Identifier expected.ts(1003)

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