Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the `in` keyword do in typescript?

Tags:

typescript

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.

like image 872
jddxf Avatar asked May 07 '18 12:05

jddxf


People also ask

What is in in JS?

The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists. Anatomy of a simple JavaScript object.

Is in array TypeScript?

To check if a value is an array of specific type in TypeScript: Use the Array. isArray() method to check if the value is an array. Iterate over the array and check if each value is of the specific type.

What is keyword type in TypeScript?

Type keyword in typescript: In typescript the type keyword defines an alias to a type. We can also use the type keyword to define user defined types.

What is symbol in TypeScript?

symbol is a primitive data type in JavaScript and TypeScript, which, amongst other things, can be used for object properties. Compared to number and string , symbol s have some unique features that make them stand out.


1 Answers

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 } 

Edit

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; } 
like image 180
Titian Cernicova-Dragomir Avatar answered Oct 09 '22 17:10

Titian Cernicova-Dragomir