gpt4 book ai didi

复合类型中的 TypeScript 字符串联合类型推断问题

转载 作者:行者123 更新时间:2023-12-04 10:45:48 25 4
gpt4 key购买 nike

我有以下代码不能用 TypeScript 编译器编译 3.7.3

type Fruit = 'apple' | 'banana'

const val = 'apple'

// Works. TS remembers the value of `val`
const fruit: Fruit = val

type Basket = {
fruit: Fruit
}

const obj = {
fruit: 'apple'
}

// Error: Type 'string' is not assignable to type 'Fruit'.
// TS probably discarded that `fruit` property has concrete value and treats it as any `string`.
const structuralBasket: Basket = obj

// This works
const declaredBasket: Basket = {
fruit: 'apple'
}

我需要 obj保持原样。我不能做的,而不是在答案中寻找:
  • 使用枚举
  • 申报 obj作为 Basket

  • 这是 TypeScript 编译器的限制吗?

    如果是这样,是否有解决方法?将来会解决这个问题吗?

    最佳答案

    问题是,当你刚刚声明 obj 时它的类型比 Fruit 更宽是,所以你得到的是 {fruit: string} ,自然不能分配给它的子类型。您可以添加 as const

    const obj = {
    fruit: 'apple'
    } as const

    这样的构造将被推断为 {fruit: 'apple'} ,什么已经可以分配给 Basket是它的亚型。

    您还可以通过值构造函数创建此类对象。考虑:
    const makeBasket = (fruit: Fruit): Basket => ({fruit})
    const obj = makeBasket('apple'); // Basket object

    关于复合类型中的 TypeScript 字符串联合类型推断问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59714310/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com