Typescript:typeof 的输出是否存在字符串文字类型的联合?

标签 typescript

我知道 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 Playground Link

关于Typescript:typeof 的输出是否存在字符串文字类型的联合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66426053/

相关文章:

typescript - 使用 browserify + babelify + tsify 缺少 TypeScript 类型

angular - 当 RowData 更改时,Angular 中的 Ag-grid 不会刷新

reactjs - '类型错误 : Converting circular structure to JSON' in a Lerna workspace with CRA and Typescript

typescript - 错误 TS4058 : Return type of exported function has or is using name X from external module Y but cannot be named

javascript - 类型 'subtle' 上不存在属性 'typeof webcrypto'

javascript - 为什么我的嵌套折叠元素没有触发 "show/shown/hide/hidden.bs.collapse"?

reactjs - 类型 'typeof test' 的参数不可分配给类型 'Component<{ children?: ReactNode; } & DispatchProp<any>>' 的参数

angular - 使用 angular2 http 服务缓存结果

typescript - Typescript 中的 Map<String,String> Dart 等价物?

javascript - 重新连接私有(private) Typescript 类方法