What does the symbol "ampersand (&)" in TypeScript type definitions mean?
P粉668804228
P粉668804228 2023-08-22 17:25:53
0
2
353
<p>In line 60359 of this type definition file, there is the following statement: </p> <pre class="brush:php;toolbar:false;">type ActivatedEventHandler = ( ev: Windows.ApplicationModel.Activation.IActivatedEventArgs & WinRTEvent<any> ) => void;</pre> <p>In this context, what does the <code>&</code> symbol mean? </p>
P粉668804228
P粉668804228

reply all(2)
P粉578343994

Intersection types in Typescript

  • A & represents an intersection type in a type context in TS.
  • It merges all properties of two object types together and creates a new type.

example:

type dog = {age: number, woof: Function};
type cat = {age: number, meow: Function};

// 类型weird是cat和dog的交集
// 它需要具有它们的所有属性的组合
type weird = dog & cat;

const weirdAnimal: weird = {age: 2, woof: () => {'woof'}, meow: () => {'meow'}}

interface extaprop {
    color: string
}

type catDog = weird & extaprop; // 类型现在还添加了color属性
const weirdAnimal2: catDog = {age: 2, woof: () => {'woof'}, meow: () => {'meow'}, color: 'red'}


// 这与联合类型不同
// 下面的类型表示猫或狗
type dogOrCat = dog | cat;
P粉148434742

& represents the intersection type in the type position.

More TypeScript documentation on intersection types:

https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types

Quoted from the above document:

interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}

interface ArtworksData {
  artworks: { title: string }[];
}

interface ArtistsData {
  artists: { name: string }[];
}

// 这些接口被组合在一起,以具有
// 一致的错误处理和它们自己的数据。

type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;

const handleArtistsResponse = (response: ArtistsResponse) => {
  if (response.error) {
    console.error(response.error.message);
    return;
  }

  console.log(response.artists);
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!