Open ExE-Boss opened 4 years ago
Given that unknown
could be defined as primitive | object
, and primitive
could be defined as null | undefined | {}
, this seems like a pretty obvious addition.
{}
includes object
, so you’d want null | undefined | ({} & not object)
aha, good point
This is obviously coherent but the use case doesn't make sense to me. You support every primitive type except one, yet claim to be able to support any future primitive that appears? How can someone possibly know that the next primitive that gets added doesn't share the same characteristics of the one they don't support?
For this specific use case that's true - I think primitive
is warranted regardless of this use case (typing a function that takes, or returns, a primitive, for example).
Even with object
, you can't know that every object will necessarily work; the language has exotic objects that don't conform to what normal objects do.
@RyanCavanaugh
How can someone possibly know that the next primitive that gets added doesn't share the same characteristics of the one they don't support?
The strong arguments for this I would see are:
valueOf
, require that a primitive and only a primitive be returned. And that type would hold true (presumably) even if JavaScript adds another primitive (such as Tuples and Records). Meaning: the correct output type of Object.prototype.valueOf() is primitive
, regardless of whether or not it exists in TypeScript. (It looks like, currently, lib.es5.d.ts
, defines valueOf() as returning Object
, which I guess is possible, but is ultimately contrary to spec.)
Search Terms
Suggestion
primitive
would be a union of all primitive types, e.g.:The advantage of doing this as a TypeScript built‑in rather than defining it in user space is that when a new primitive type gets added to ECMAScript (e.g.:
bigdecimal
), it will be supported automatically without needing to update the type definitions of the library.Use Cases
When describing an API that takes all‑but‑one primitive type, it’s useful to be able to do
Exclude<primitive, symbol>
orExclude<primitive, number | bigint>
without needing https://github.com/microsoft/TypeScript/pull/29317.Examples
Checklist
My suggestion meets these guidelines:
Related