繁体   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