<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          TS 索引訪問類型

          共 1135字,需瀏覽 3分鐘

           ·

          2023-01-07 00:11


          我們可以使用索引訪問類型來查找另一種類型的特定屬性:

          type Person = { age: number; name: string; alive: boolean };type Age = Person["age"];
          // type Age = number


          索引類型本身就是一種類型,因此我們可以與聯(lián)合類型、keyof 或其他類型配合使用:

          type I1 = Person["age" | "name"];
          // type I1 = string | number
          type I2 = Person[keyof Person];
          // type I2 = string | number | boolean
          type AliveOrName = "alive" | "name";type I3 = Person[AliveOrName];
          // type I3 = string | boolean


          如果嘗試索引不存在的屬性,您會看到有報(bào)錯(cuò):

          type I1 = Person["alve"];
          // Property 'alve' does not exist on type 'Person'.


          使用數(shù)字獲取數(shù)組元素的類型。我們可以將其與 typeof 結(jié)合起來,可以方便地獲取數(shù)組里面的元素類型:

          const MyArray = [  { name: "Alice", age: 15 },  { name: "Bob", age: 23 },  { name: "Eve", age: 38 },];
          type Person = typeof MyArray[number];
          // type Person = {name: string;age: number;}
          type Age = typeof MyArray[number]["age"];
          // type Age = number
          // Ortype Age2 = Person["age"];
          // type Age2 = number


          我們只能使用類型進(jìn)行索引,這意味著不能使用變量引用:

          const key = "age";type Age = Person[key];
          // Type 'key' cannot be used as an index type.// 'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?


          但是,您可以使用類型別名:

          type key = "age";type Age = Person[key];


          瀏覽 49
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  天天干,天天射免费视频 | 青娱乐精品在线视频 | A片视频免费观看 | 丁香五月婷婷色 | 成人黄色AV网站 |