我知道 typeof 的输出类型是字符串。
在 typescript 中有这种模式,称为 "Union of string literal types" :
export type Fruit = 'banana' | 'apple' | 'orange';
问:是否存在任何库中存在的可导入字符串文字类型联合,以确保字段只能是 typeof 运算符的可能输出?
示例伪代码:
import {JSType} from '@somelib/types'; // <--- what I want, this is a bogus type/lib
export class SomeClass {
data: any;
type: JSType;
constructor (params) {
this.data = params.data;
this.type = typeof params.data;
}
render = () => {
switch(this.type){
case 'boolean':
// return checkbox html component
// more type cases
default:
// return input html component
}
}
}
我可以手动创建我需要的类型,但我更愿意让比我更聪明的人来处理该类型的维护,以及如果 JS/TS 添加除“字符串”之外的某些类型的 future 证明 | '数字' | '功能' | '对象' | '未定义'。
另外,在紧要关头,如果我需要添加自定义类型,那么我可以 extend the existing type , 以包含我需要的字符串。
编辑 #1: 更新了术语。感谢 jcalz
最佳答案
必须有更好的方法来做到这一点,因为这些定义已经存在于某处。但是我们可以通过一种非常迂回的方式访问联合:
- 创建类型为
any
的变量 - 对该变量调用 JS
typeof
,这将返回所有可能类型的联合 - 创建一个使用 TS
typeof
将该联合作为类型访问的 typescript 类型。
const x: any = "";
const t = typeof x;
type TypeofTypes = typeof t;
这创造了
type TypeofTypes = "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
关于Typescript:typeof 的输出是否存在字符串文字类型的联合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66426053/