AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 78783536
Accepted
Oktay Yuzcan
Oktay Yuzcan
Asked: 2024-07-23 20:51:06 +0800 CST2024-07-23 20:51:06 +0800 CST 2024-07-23 20:51:06 +0800 CST

不同枚举的通用函数

  • 772

我有多个枚举

const enum E1 {
    CLOSED = 'CLOSED',
    OPEN = 'OPEN',
    IN_PROGRESS = 'IN_PROGRESS',
}

const enum E2 {
    OPEN = 'OPEN',
    CLOSED = 'CLOSED',
    IN_PROGRESS = 'IN_PROGRESS',
}

const enum E3 {
    OPEN = 'OPEN',
    IN_PROGRESS = 'IN_PROGRESS',
}

我想创建一个接受枚举的函数,其中一个值应该是“CLOSED”

const func = (value: 'CLOSED') => {...}
interface Data1 {status: E1}
interface Data2 {status: E2}
interface Data3 {status: E3}
const o1: Data1 = {status: E1.CLOSED}
const o2: Data2 = {status: E2.OPEN}
const o3: Data3 = {status: E3.OPEN}

func(o1.status)   // this should be valid. status is type E1, it contains 'CLOSED'
func(o2.status)   // this should be valid. status is type E2, it contains 'CLOSED'
func(o3.status)   // this should be invalid. status type is E3, it does not contain 'CLOSED'

但它会为每个对象引发一个错误:

Argument of type E... is not assignable to parameter of type "CLOSED"

我不希望该函数知道每个枚举,因为它们有很多。这就是为什么我使用类型value: 'CLOSED'

我是否需要像通用枚举这样的东西来让其他人以某种方式扩展它,以便我可以在参数中使用它的类型而不是“CLOSED”?

Typescript 版本:4.9.4

typescript
  • 2 2 个回答
  • 41 Views

2 个回答

  • Voted
  1. Best Answer
    jcalz
    2024-07-23T23:57:25+08:002024-07-23T23:57:25+08:00

    枚举具有一些奇怪的类型系统行为,这使其变得更加复杂。现在,我们只使用普通的字符串文字类型而不是枚举,然后我们就可以回到它。我们现在可以用const断言对象和类型别名E1替换您的枚举定义。看起来像

    const E1 = {
        CLOSED: 'CLOSED',
        OPEN: 'OPEN',
        IN_PROGRESS: 'IN_PROGRESS',
    } as const
    type E1 = typeof E1[keyof typeof E1]
    

    其它的也类似。


    类型(value: "CLOSED") => void不适合您,因为这意味着您传入的任何东西都value必须可分配给文字类型"CLOSED"。这与您想要的正好相反。相反,您想说必须"CLOSED"可分配给类型。您不想从上方value限制类型(例如,它必须是或某种较窄的类型),而是想从下方限制它(例如,它必须是或某种较宽的类型)。value"CLOSED""CLOSED"

    不幸的是,TypeScript 本身并不支持这种下限类型约束。TypeScript 的约束(例如T extends U)是上限。microsoft /TypeScript#14520有一个开放功能请求,允许下限约束(例如T super U)。如果这是 TypeScript 的一部分,那么我认为你可以写

    // not valid TS, don't try this:
    const func = <T extends string super 'CLOSED'>(value: T) => { }
    

    就完成了。你可以value从上方用进行约束string,从下方用进行约束"CLOSED"。但你不能直接这样做。

    作为一种解决方法,您可以利用约束中的条件类型T super "CLOSED"。从概念上讲,与相同"CLOSED" extends T。因此,如果我们可以重写约束以"CLOSED" extends T强制执行,那么它可能会按照您想要的方式运行:

    const func = <T extends 'CLOSED' extends T ? string : never>(value: T) => { }
    
    func(o1.status)   // okay
    func(o2.status)   // okay
    func(o3.status)   // error
    func(Math.random() < 0.5 ? "CLOSED" : "XYZ"); // okay
    func(Math.random() < 0.5 ? "ABC" : "XYZ"); // error
    

    而且它确实有效。当您调用时func(o1.status),T推断为E1。然后约束变为'CLOSED' extends E1 ? string : never,它会折叠为string,因此约束是T extends string满足并且成功。

    但是当你调用 时func(o3.status),T被推断为E3。那么约束就变成了'CLOSED' extends E3 ? string : never,它会折叠为类型never,因此约束就是 ,它T extends never不满足并且会失败。


    如果您不使用枚举,我就会这样做。枚举使情况变得更加复杂,因为它们本身大多被视为其值的正确子类型E1.CLOSED extends "CLOSED"。所以是正确的,但"CLOSED" extends E1.CLOSED错误的是:

    type Yes = E1.CLOSED extends "CLOSED" ? true : false
    //   ^? type Yes = true
    type No = "CLOSED" extends E1.CLOSED ? true : false
    //   ^? type No = false
    

    这意味着"CLOSED"不是 的下限,即使它是字符串文字类型E1所代表的下限。我不会尝试剖析枚举,而是使用一个技巧将字符串枚举扩展为其字符串文字类型:只需使用模板文字类型来序列化它们: E1

    type E1Serialized = `${E1}`
    //   ^? type E1Serialized = "CLOSED" | "OPEN" | "IN_PROGRESS"
    

    "CLOSED"的下限也是如此E1Serialized。这意味着我们可以将func其改为

    const func = <T extends 'CLOSED' extends `${T}` ? string : never>(value: T) => { }
    

    一切正常:

    func(o1.status)   // okay
    func(o2.status)   // okay
    func(o3.status)   // error
    func(Math.random() < 0.5 ? "CLOSED" : "XYZ"); // okay
    func(Math.random() < 0.5 ? "ABC" : "XYZ"); // error
    

    游乐场链接到代码

    • 1
  2. Remo H. Jansen
    2024-07-23T22:52:17+08:002024-07-23T22:52:17+08:00

    这对你有用吗?

    1. 创建联合类型(字符串文字类型)而不是枚举类型:
    type CLOSED<T extends string> = `${T}.CLOSED`;
    type OPEN<T extends string> = `${T}.OPEN`;
    type IN_PROGRESS<T extends string> = `${T}.IN_PROGRESS`;
    
    type EWithClosed<T extends string> = CLOSED<T> | OPEN<T> | IN_PROGRESS<T>;
    type EWithoutClosed<T extends string> = Exclude<EWithClosed<T>, CLOSED<T>>;
    
    1. 创建可以在运行时使用的值:
    const makeClosed = <T extends string>(k: T): CLOSED<T> => `${k}.CLOSED`;
    const makeOpen = <T extends string>(k: T): OPEN<T> => `${k}.OPEN`;
    const makeInProgress = <
        T extends string
    >(k: T): IN_PROGRESS<T> => `${k}.IN_PROGRESS`;
    
    const makeWithClosed = <T extends string>(k: T) => ({
      CLOSED: makeClosed(k),
      OPEN: makeOpen(k),
      IN_PROGRESS: makeInProgress(k)
    });
    
    const makeWithoutClosed = <T extends string>(k: T) => ({
      CLOSED: makeClosed(k),
      OPEN: makeOpen(k)
    });
    
    const E1 = makeWithClosed("E1");
    const E2 = makeWithClosed("E2");
    const E3 = makeWithoutClosed("E3");
    
    1. 然后我们可以使用类型和值:
    const o1 = {status: E1.CLOSED }
    const o2 = {status: E2.OPEN }
    const o3 = {status: E3.OPEN }
    
    const func = <T extends string>(value: CLOSED<T>) => {
      // ...
    }
    
    func(o1.status)   // OK
    func(o2.status)   // ERROR
    func(o3.status)   // ERROR
    

    查看此演示

    • 0

相关问题

  • 为什么我们在条件语句中使用方括号“[]”?

  • Nestjs有关模块的问题

  • 如何获取文件的打字稿元数据?

  • 如何将数组转换为像这样的对象返回 const 类型?

  • “没有重载匹配”我的 Object.assign() 调用;我该如何修复它?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve