本文介绍了在TypeScript中扩展字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When using generics in TypeScript, you sometimes see a type Parameter such as:

T extends string

这与直接使用字符串不一样吗?您可以将字符串归类吗?这有什么好处?

Isn’t this the same as using string directly? Can you subclass string? What would this be good for?

推荐答案

type narrowedString =  "foo" | "bar"

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

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

"foo" and "bar" extend both the string type. For example that is useful, when you want to define enum like data structures (without the built in TypeScript enum type) or constants.

当函数提供扩展字符串的通用类型参数(如 T扩展字符串)时,您可以使用该参数为枚举/常量强制强类型.

When a function offers a generic type parameter which extends string like T extends string, you can use that to enforce strong typing for your enums/constants.

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

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

将TypeScript的类型系统中的 extends 与ES类中的 extends 组合在一起,不会犯错误-它们是两个完全不同的运算符.

Don't make the mistake to lump extends in TypeScript's typesystem together with extends from ES classes - they are two complete distinct operators.

class extends 对应于 instanceof ,并在运行时作为构造存在,而在类型系统中 extends 例如.与条件类型一起发生,可以翻译为可分配给",并且仅用于编译时.

class extends corresponds to instanceof and exists in the runtime as a construct, whereas in the type system extends e.g. occurs with Conditional types,can be translated with "is assignable to" and is only for compile time.

更新:

您可以在 TypeScript文档.

这篇关于在TypeScript中扩展字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 12:32