gpt4 book ai didi

javascript - 在 TypeScript 中扩展字符串

转载 作者:行者123 更新时间:2023-11-30 08:18:49 26 4
gpt4 key购买 nike

在 TypeScript 中使用泛型时,有时会看到类型参数,例如:

T extends string

这和直接用string不一样吗?你能继承字符串吗?这有什么用?

最佳答案

type narrowedString =  "foo" | "bar"

// type ExtendsString = true
type ExtendsString = "foo" extends string ? true : false

“foo”和“bar”都扩展了字符串类型。例如,当您想定义枚举之类的数据结构(没有内置 TypeScript 枚举类型)或常量时,这很有用。

当函数提供扩展字符串的泛型类型参数时,如 T extends string,您可以使用它来为您的枚举/常量强制执行强类型。

function doSomething<T extends string>(t: T): {a: T} {
...
}

// invoke it
doSomething("foo" as const) // return {a: "foo"}

不要错误地将 TypeScript 类型系统中的 extends 与来自 ES 类的 extends 混为一谈——它们是两个完全不同的运算符。

class extends 对应于 instanceof 并作为构造存在于运行时,而在类型系统中 extends 例如与 Conditional types 一起发生,可以翻译为“is assignable to”,仅供编译时使用。

更新:

您可以在 TypeScript docs 中找到有关字符串文字类型的更多信息.

关于javascript - 在 TypeScript 中扩展字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57342018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com