Type queries allow us to obtain type information from values, which is an incredibly important capability — particularly when working with libraries that may not expose type information in a way that’s most useful for you
keyof
The keyof
type query allows us to obtain type representing
all property keys on a given interface
tsTry
typeDatePropertyNames = keyofDate
Not all keys are string
s, so we can separate out
those keys that are symbol
s and those that are string
s
using the intersection operator (&
).
If you remember your geometry, it may be useful to think of this
as kind of like a dot product, in that when we use the intersection
operator, we’re left only with the sub-part of the keyof Date
that also is included by string
or symbol
, respectively.
tsTry
typeDatePropertyNames = keyofDate typeDateStringPropertyNames =DatePropertyNames & stringtypeDateSymbolPropertyNames =DatePropertyNames & symbol
Interesting! this Symbol.toPrimitive
property
is the only non-string. 1
typeof
The typeof
type query allows you to extract a type from a value. An example is shown below
tsTry
async functionmain () {constapiResponse = awaitPromise .all ([fetch ("https://example.com"),Promise .resolve ("Titanium White"),])typeApiResponseType = typeofapiResponse }
A common use of typeof
is to obtain a type representing the “static site” of a class (meaning: constructor, static
properties, and other things not present on an instance of the class)
tsTry
classFruit {constructor(public readonlyname : string,public readonlymass : number,public readonlycolor : string) {}staticcreateBanana () {return newFruit ("banana", 108, "yellow")}}constMyFruit =Fruit constbanana =Fruit .createBanana ()
MyFruit
, the class (constructor) is of type typeof Fruit
, where instances are of type Fruit
-
If you’re curious about this property, try running the following in your terminal
↩node -e "console.log(new Date()[Symbol.toPrimitive]('string'))"