Rachelle Rathbone

TypeScript - Type Queries

typeof and keyof

March 26, 2023

TypeScript type queries are used to obtain information from values which can really come in handy when we aren't completely sure of the typing of the data we're working with.

typeof

You know how sometimes you want to type something in your code but aren't sure exactly what the type contains? This is where the typeof type query comes into play and we use it just like we would to confirm any other value in our code.

In the following example we're making an API request to get some gifs from Giphy and storing that value, along with a string value. If we now wanted to create a type based on the value of response this can be easily achieved by creating a new type and utilising typeof.

const getGiphys = async () => {
const response = await Promise.all([
fetch("https://api.giphy.com/v1/gifs"),
Promise.resolve("Success!")
]);
type ResponseType = typeof response;
}

If we copy this over into the TypeScript playground we can see that ResponseType is equal to [Response, string]


keyof

This type query makes it possible to access all property keys on a given interface. Let's say we want to create a type based on the keys of TypeError. We simply start by creating a type to store all the keys for TypeError:

type TypeErrorProperties = keyof TypeError;

Then we would create another type to extract the properties that meet the condition/s we're after.

type TypeErrorStringProperties = TypeErrorProperties & string;

In the example above, we've created a new type TypeErrorStringProperties and defined it's value using the union operator &. To the right of the equals sign, we're stating 'we want all the keys from TypeErrorProperties that are also of type string'. Below we see we get 3 values back: name, message and stack.


Now if we were to try and obtain any keys that were of type number, we would see we get the value of never. This is because, for this particular example, all keys for TypeError are of type string.


...
© 2023, Rachelle Rathbone