我知道 typeof 的输出类型是字符串。
在打字稿中有这种模式,称为“字符串文字类型的联合”:
export type Fruit = 'banana' | 'apple' | 'orange';
Run Code Online (Sandbox Code Playgroud)
问:任何库中是否存在可导入的字符串文字类型联合,允许确保字段只能是 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可以手动创建我需要的类型,但我更愿意让比我更聪明的人来处理类型的维护,并且如果 JS/TS 除了“字符串”之外还添加了某种类型,那么未来的证明 '数字' | '功能' | '对象' | '不明确的'。
另外,在紧要关头,如果我需要添加自定义类型,那么我可以扩展现有类型,以包含我需要的字符串。
编辑#1:更新术语。感谢 jcalz
必须有更好的方法来做到这一点,因为这些定义已经存在于某处。但我们可以通过一种非常迂回的方式访问联盟:
anytypeof,这将返回所有可能类型的并集typeof来访问该联合作为类型的打字稿类型。const x: any = "";
const t = typeof x;
type TypeofTypes = typeof t;
Run Code Online (Sandbox Code Playgroud)
这创造了
type TypeofTypes = "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
676 次 |
| 最近记录: |