如何将打字稿类型声明为 "variable" 以供重复使用?

How to declare typescript type as "variable" for repeated use?

我现在正在学习打字稿,我知道你可以做什么 (这只是一个简化的例子):

interface IExample1 { 
  Value: String | Number | String[] | Number [] 
}

interface IExample2 { 
  Value: String | Number | String[] | Number [] 
}

IExample1IExample2value 具有相同的类型。有没有办法以某种方式声明 Value 的类型并在需要时重用它?

看起来像这样:

ValueType = String | Number | String[] | Number [] 

interface IExample1 { 
  Value: ValueType
}

interface IExample2 { 
  Value: ValueType
}

出于某种原因,我找不到任何相关内容(不确定要搜索什么)

试试下面的代码

type valueType = String | Number | String[] | Number []

interface IExample1 { 
  Value: valueType
}

interface IExample2 { 
  Value: valueType
}

来自文档:

Type aliases create a new name for a type. Type aliases are sometimes similar to interfaces, but can name primitives, unions, tuples, and any other types that you’d otherwise have to write by hand.

type ValueType = String | Number | String[] | Number [] 

interface IExample1 { 
  Value: ValueType
}

interface IExample2 { 
  Value: ValueType
}

Playground Link

没有创建新类型,只是为该类型创建了一个新名称。

首先,我敢打赌,对于这个简单的案例,您不需要使用像 NumberString 这样的构造函数类型。您应该改用 stirngnumber。请参阅 docs

Number类型指的是纯js中的Number构造函数,而number指的是原始类型。

如果想避免重复,可以使用distributive-conditional-types:

type ValueType<T> = T extends any ? T | T[] : never

type Value = ValueType<string | number>

interface IExample1 {
    Value: Value
}

interface IExample2 {
    Value: Value
}

Playground