What does the `in` keyword do in typescript?


Typescript Problem Overview

I know how to use it, but I cannot find any explanation on it in docs. I'd like an accurate definition so that I could understand it better.

Edit: I mean the in used in mapped types, not the js operator.

Typescript Solutions

Solution 1 - Typescript

This is the standard in Javsacript operator. You can read more documentation here, but the short story is

> The in operator returns true if the specified property is in the specified object. The syntax is: > > propNameOrNumber in objectName >where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

In Typescript the in operator also acts as a type guard as described here

interface A {
  x: number;
interface B {
  y: string;

let q: A | B = ...;
if ('x' in q) {
  // q: A
} else {
  // q: B


An alternative meaning of in in typescript is in mapped type definition. You can read about them in the handbook or in the pull request. The in keyword is used there as part of the syntax to iterate over all the items in a union of keys.

interface Person {
    name: string;
    age: number;
type Partial<T> = {
    [P in keyof T]?: T[P]; // P will be each key of T
type PersonPartial = Partial<Person>; // same as { name?: string;  age?: number; }


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjddxfView Question on Stackoverflow
Solution 1 - TypescriptTitian Cernicova-DragomirView Answer on Stackoverflow