簡體   English   中英

強制更改字符串遵循 Typescript 類型聯合

[英]Enforce altering string adheres to Typescript type union

我有一個需要以下類型的庫:

type Strings = "A" | "B"

有時我會得到一個簡單的字符串,如“A”或“B”,有時我會得到“summedA”或“summedB”。 如果更改字符串,我如何說服 typescript 確保我正確格式化它? 例如:

functionThatRequiresType(input: Strings) {...}

const string: string = "summedA"

const newString = string.replace("summed", "")

functionThatRequiresType(newString) => calling throws error

您可以告訴 TypeScript string.replace("summed", "")使用as返回Strings類型的值。

示例

type Strings = "A" | "B"

function functionThatRequiresType(input: Strings) {}

const string: string = "summedA"

const newString = string.replace("summed", "") as Strings

functionThatRequiresType(newString)

您可以使用類型轉換:

const newString = string.replace("summed", "") as Strings

但是,這樣做可能會削弱類型系統,因為 TypeScript 會相信您的類型轉換在大多數情況下是正確的。

因此,您必須謹慎使用類型轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM