Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript & operator

Tags:

typescript

I'm struggling to find the definition of the & operator in TypeScript. I have recently come across the following code:

type IRecord<T> = T & TypedMap<T>; 

What does that operator do, and how is it different from the union type |?

like image 584
ppoliani Avatar asked Nov 23 '15 16:11

ppoliani


People also ask

What is TypeScript used for?

TypeScript is a superset of typed JavaScript (optional) that can help build and manage large-scale JavaScript projects. It can be considered JavaScript with additional features like strong static typing, compilation, and object-oriented programming.

Is TypeScript better than JavaScript?

1. TypeScript is more reliable. In contrast to JavaScript, TypeScript code is more reliable and easier to refactor. This enables developers to evade errors and do rewrites much easier.

Is TypeScript frontend or backend?

Is TypeScript Frontend or Backend? TypeScript is neither a frontend or backend language, but rather a superset of the already established and well-known software language, JavaScript.

Is TypeScript and JavaScript same?

TypeScript is known as an Object-oriented programming language whereas JavaScript is a prototype based language. TypeScript has a feature known as Static typing but JavaScript does not support this feature. TypeScript supports Interfaces but JavaScript does not.


1 Answers

This looks like it's from the Intersection Types portion of the Language Specification. Specifically, the & is an intersection type literal. As for what it does:

Intersection types represent values that simultaneously have multiple types. A value of an intersection type A & B is a value that is both of type A and type B. Intersection types are written using intersection type literals (section 3.8.7).

The spec goes on to offer a helpful snippet to better understand the behavior:

interface A { a: number }   interface B { b: number }  var ab: A & B = { a: 1, b: 1 };   var a: A = ab;  // A & B assignable to A   var b: B = ab;  // A & B assignable to B 

Because ab is both of type A and of type B, we can assign it to a and/or b. If ab were only of type B, we could only assign it to b.

The code you shared may be from this comment on GitHub, which mentions Intersection Types.

like image 66
Sampson Avatar answered Sep 27 '22 18:09

Sampson