付費限定文章
Unions and Intersection Types

閱讀時間約 11 分鐘

So far, the handbook has covered types which are atomic objects. However, as you model more types you find yourself looking for tools which let you compose or combine existing types instead of creating them from scratch.

Intersection and Union types are one of the ways in which you can compose types.

Union Types

Occasionally, you’ll run into a library that expects a parameter to be either a number or a string. For instance, take the following function:

/** * Takes a string and adds "padding" to the left. * If 'padding' is a string, then 'padding' is appended to the left side. * If 'padding' is a number, then that number of spaces is added to the left side. */function padLeft(value: string, padding: any) {  if (typeof padding === "number") {    return Array(padding + 1).join(" ") + value;  }  if (typeof padding === "string") {    return padding + value;  }  throw new Error(`Expected string or number, got '${typeof padding}'.`);} padLeft("Hello world", 4); // returns "    Hello world"Try

The problem with padLeft in the above example is that its padding parameter is typed as any. That means that we can call it with an argument that’s neither a number nor a string, but TypeScript will be okay with it.

// passes at compile time, fails at runtime.let indentedString = padLeft("Hello world", true);Try

In traditional object-oriented code, we might abstract over the two types by creating a hierarchy of types. While this is much more explicit, it’s also a little bit overkill. One of the nice things about the original version of padLeft was that we were able to just pass in primitives. That meant that usage was simple and concise. This new approach also wouldn’t help if we were just trying to use a function that already exists elsewhere.

Instead of any, we can use a union type for the padding parameter:

/** * Takes a string and adds "padding" to the left. * If 'padding' is a string, then 'padding' is appended to the left side. * If 'padding' is a number, then that number of spaces is added to the left side. */function padLeft(value: string, padding: string | number) {  // ...} let indentedString = padLeft("Hello world", true);Argument of type 'boolean' is not assignable to parameter of type 'string | number'.Argument of type 'boolean' is not assignable to parameter of type 'string | number'.Try

A union type describes a value that can be one of several types. We use the vertical bar (|) to separate each type, so number | string | boolean is the type of a value that can be a number, a string, or a boolean.

Unions with Common Fields

If we have a value that is a union type, we can only access members that are common to all types in the union.

以行動支持創作者!付費即可解鎖
本篇內容共 4550 字、0 則留言,僅發佈於海象你目前無法檢視以下內容,可能因為尚未登入,或沒有該房間的查看權限。
    3會員
    45內容數
    海豹
    留言0
    查看全部
    發表第一個留言支持創作者!
    kuanting的沙龍 的其他內容
    123
    閱讀時間約 1 分鐘
    什麼!這個居然 ⋯⋯
    閱讀時間約 1 分鐘
    disney
    閱讀時間約 1 分鐘
    我公開囉12
    閱讀時間約 1 分鐘
    隱藏發佈你看不到
    閱讀時間約 1 分鐘
    你可能也想看
    SQL 程式札記 : 聯集(UNION)本文重點介紹 SQL 中的聯集(UNION),聯集(UNION)用於合併來自不同查詢的結果集,接下來將透過範例程式碼來讓你了解聯集(UNION)的用法和特性。
    Thumbnail
    avatar
    梧笙
    2023-12-25
    【跑吧】The Union Trading Company|上海徐匯餐酒|初訪 接地氣才會使得不同城市的人來到上海 知道這城市總有那麼個地方--The Union Trading Company 能度過說不上消磨寂寞卻感到有點溫暖的夜上海
    Thumbnail
    avatar
    iRainy
    2023-07-11
    緬甸聯邦共和國 Republic of the Union of Myanmar緬甸聯邦共和國 Republic of the Union of Myanmar
    Thumbnail
    avatar
    JAD
    2023-06-03
    第一次踏入世界名廚餐廳丨Jamie Oliver Union Jack2016年到訪英國時,Jamie Oliver全球名聲正旺!即便Gordon Ramsay才是貨真價實的廚師,在名氣及資產上依然比不上他。世界上有些事是沒道理可言的,有實力的人不一定會擁有最好的名利。
    Thumbnail
    avatar
    北漂。長住 | 習慣用濾鏡欣賞生活的美
    2023-05-12
    愛爾蘭威士忌與接骨木花的結合:注重風味流動的Cooper Union這是一杯適合推薦給喜歡經典調酒的你,沒有過多的裝飾或香氛,只是單純品飲威士忌的風味以及其中輕盈,好似人間無苦難的感覺。細緻的甜感來自於聖傑曼接骨木花利口酒,帶出絕對清新的花香、果香,令人難以忘懷。自從認識了這一杯相對來說較為近代的調酒,我越來越能理解威士忌除了純飲外,以調酒的方式呈現更是別出心裁。
    Thumbnail
    avatar
    朵拉朵朵拉
    2023-04-26
    【European Union Plans Pilot Project on DeFi Supervision】从长远来看,监管机构通过读取公共区块链数据自动监控合规性的能力可以大大减少市场参与者积极收集、验证并向监管机构交付数据的需求。 #defi #europeanunion
    Thumbnail
    avatar
    Talk_DeFi
    2022-05-12
    【美食地圖】台北中山|Double Single Union|美式餐廳裡超好吃炸雞(含菜單)Double Single的店門口就可以看到菜單了,種類很單純有薯條、炸雞、pizza、義大利麵、飲料幾種常見品項,輕食價位落在100-300之間,飲料在100元有找,價格蠻有競爭力的。 結論
    Thumbnail
    avatar
    美食雷達凱西
    2022-03-29
    讀 The Union of Synchronised Swimmers六個在香菸工廠工作的女孩,為了逃離苦練水上芭蕾。趁著奧運她們成功地離開蘇聯統治的家鄉,The Union of Synchronised Swimmers 以六篇速寫式的短篇勾勒出她們逃離後的生活。
    Thumbnail
    avatar
    Shoé
    2021-09-11
    美國出差 第五章 Great Mall.Stoneridge shopping center and Union Square若只是要買我自己要穿的還簡單,但還要買親友的,就很麻煩,這麼大的Great Mall只有入口處有Wifi,所以我只能在那裡,可以用Wifi跟台灣的採購總指揮確認要買的東西,導致我必須走到店家去拍照,走回門口去傳圖確認無誤後,再回去購物。 檢視較大的地圖 下面這袋就是我快三的小時所買的一大袋衣服
    Thumbnail
    avatar
    老李.你今天都在幹嘛?
    2013-06-09