Skip to main content

Type Operators

TypeScript introduces several type operators and constructs that enable powerful and flexible type transformations. These operators are essential tools in the TypeScript type system, allowing for the creation of complex and expressive type definitions. Here's a comprehensive list:

  • keyof: Produces a union type of the keys (property names) of an object type.

  • typeof: When used in a type context, captures the type of a variable or property, rather than its value.

  • extends: Used in conditional types to test whether a type extends another type, enabling different types to be chosen based on that condition.

  • infer: Used within the extends clause of conditional types to infer types from other types, useful in advanced type manipulation scenarios.

  • in: Used in mapped types to iterate over the keys of a given type, allowing the construction of new types based on the keys of an existing type.

  • as: Type assertion, not really an operator per se, but allows you to treat a variable as a different type than the one TypeScript inferred.

  • |: Union type, used to define a type that can be one of several types.

  • &: Intersection type, used to combine multiple types into one.

  • ?: Used in two contexts: as an optional property marker in object types, and in conditional types to define the true and false branches.

  • !: Non-null assertion operator, used to assert that an expression is non-null and non-undefined.

keyof​

In TypeScript, you can use the keyof operator to get the keys of an object as a type. Here's a basic example:

interface MyObject {
foo: string;
bar: number;
baz: boolean;
}

type MyObjectKeys = keyof MyObject; // "foo" | "bar" | "baz"

In this example, MyObjectKeys will be a type that is equivalent to the union of the string literals "foo", "bar", and "baz".

Here's another example with a function that takes an object and a key and returns the value:

function getValue<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}

const myObj = {
name: "John",
age: 30,
};

const name = getValue(myObj, "name"); // type of name will be inferred as string
const age = getValue(myObj, "age"); // type of age will be inferred as number

In this function, K extends keyof T ensures that key must be one of the keys of obj.

This allows TypeScript to maintain type safety.