搜尋

首頁  >  問答  >  主體

TypeScript類型定義中的符號 "ampersand (&)" 代表什麼意義?

<p>在此類型定義檔的60359行,有以下聲明:</p> <pre class="brush:php;toolbar:false;">type ActivatedEventHandler = ( ev: Windows.ApplicationModel.Activation.IActivatedEventArgs & WinRTEvent<any> ) => void;</pre> <p>在這個上下文中,<code>&</code>符號表示什麼意思? </p>
P粉668804228P粉668804228542 天前467

全部回覆(2)我來回復

  • P粉578343994

    P粉5783439942023-08-23 09:47:27

    在Typescript中的交集類型

    • A & 在TS中的類型上下文中表示交集類型。
    • 它將兩個物件類型的所有屬性合併在一起,並建立一個新類型。

    範例:

    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;

    回覆
    0
  • P粉148434742

    P粉1484347422023-08-23 00:44:51

    &在型別位置表示交集型別。

    更多關於交集類型的TypeScript文件:

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

    引用自上述文件:

    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);
    };

    回覆
    0
  • 取消回覆