[英]The const assertion seems that the type can't be assigned to the type any[] for the generic parameter
export const CHRONIC_CHANNEL_LEVELS = [
{ label: 'one', value: '1' },
{ label: 'two', value: '2' },
] as const;
export type ElementType<T extends any[]> = T extends (infer U)[] ? U : never;
type ChronicChannelLevel = ElementType<typeof CHRONIC_CHANNEL_LEVELS>['value']; // throw error
TSC throws an error: TSC 抛出错误:
Type 'readonly [{ readonly label: "one"; readonly value: "1"; }, { readonly label: "two"; readonly value: "2"; }]' does not satisfy the constraint 'any[]'.
The type 'readonly [{ readonly label: "one"; readonly value: "1"; }, { readonly label: "two"; readonly value: "2"; }]' is 'readonly' and cannot be assigned to the mutable type 'any[]'.(2344)
The const
assertion seems that the type can't be assigned to the type any[]
for the generic parameter. const
断言似乎不能将类型分配给泛型参数的类型any[]
。
I want the type ChronicChannelLevel
to be a union type '1' | '2'
我希望ChronicChannelLevel
类型是联合类型'1' | '2'
'1' | '2'
. '1' | '2'
。
I know I can use typeof CHRONIC_CHANNEL_LEVELS[number]['value']
, but I want to create a utility type like ElementType
to get the element type from an array.我知道我可以使用typeof CHRONIC_CHANNEL_LEVELS[number]['value']
,但我想创建一个像ElementType
这样的实用程序类型来从数组中获取元素类型。
By accepting that tuple/array and readonly tuple/array are fundamentally different types, we can make progress:通过接受元组/数组和只读元组/数组是根本不同的类型,我们可以取得进展:
export type ElementType<T extends (any[] | readonly any[])> =
T extends (infer U)[] ?
U :
T extends readonly (infer U)[] ?
U :
never
...or by introducing a new type: ...或通过引入一种新类型:
export type ArrayType<T> = T[] | readonly T[]
export type ElementType<T extends ArrayType<any>> =
T extends ArrayType<infer U> ?
U :
never
we can simplify the amount of inference and branching required for the conditional type我们可以简化条件类型所需的推理和分支量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.