sách gpt4 ăn đã đi

typescript - 为什么元组推理从 any[] 变成 [string, string, ... ] 而从 string[] 变成 ['literal1' , 'literal2' , ... ]

In lại 作者:搜寻专家 更新时间:2023-10-30 21:26:43 28 4
mua khóa gpt4 giày nike

我已经阅读了这个答案https://stackoverflow.com/a/45486495/1108891 ,它演示了元组类型推断。经过一些实验,我遇到了这种情况。


当我们的 bộ ba 函数有 T extends string[] 时,元组有 string literal 类型。

export const tuple_0 = (...args: T): T => args;

const ALL_SUITS_0 = tuple_0('hearts', 'diamonds', 'spades', 'clubs');

type T0 = typeof ALL_SUITS_0; // ["hearts", "diamonds", "spades", "clubs"]

另一方面,对于 T extends any[],元组具有 sợi dây 类型(不是文字)。

export const tuple_1 = (...args: T) => args;

const ALL_SUITS_1 = tuple_1('hearts', 'diamonds', 'spades', 'clubs');

type T1 = typeof ALL_SUITS_1; // [string, string, string, string]

为什么在后一种情况下我们会丢失文字类型?


我怀疑这与类型推断允许自己采取多少具体步骤有关。即bất kì距离sợi dây一步,sợi dây距离'some-string-literal'。类型推断是否只允许自己迈出一步?

câu trả lời hay nhất

这不一定特定于元组。如果类型参数具有可以具有文字类型的约束,则 Typescript 将为泛型参数推断文字类型。此行为是由 PR 引入的

来自公关:

During type argument inference for a call expression the type inferred for a type parameter T is widened to its widened literal type if [...] T has no constraint or its constraint does not include primitive or literal types

在你的问题的例子中,因为 sợi dây 是原始的,我们没有扩大,因为 bất kì 不是原始的,我们扩大了。

关于typescript - 为什么元组推理从 any[] 变成 [string, string, ... ] 而从 string[] 变成 ['literal1' , 'literal2' , ... ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53861768/

28 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress