const 断言似乎无法将类型分配给泛型参数的类型 any[]

幻灯片p2
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 抛出错误:

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)

const断言似乎无法将类型分配给泛型参数的类型any[]

我希望类型ChronicChannelLevel是联合类型'1' | '2'

我知道我可以使用typeof CHRONIC_CHANNEL_LEVELS[number]['value'],但我想创建一个实用程序类型,例如ElementType从数组中获取元素类型。

打字稿游乐场

花费者

通过接受元组/数组和只读元组/数组是根本不同的类型,我们可以取得进展:

export type ElementType<T extends (any[] | readonly any[])> =
  T extends (infer U)[] ?
  U :
  T extends readonly (infer U)[] ?
  U :
  never

游乐场链接

...或通过引入一种新类型:

export type ArrayType<T> = T[] | readonly T[]

export type ElementType<T extends ArrayType<any>> =
  T extends ArrayType<infer U> ?
  U :
  never

我们可以简化条件类型所需的推理和分支量

游乐场链接

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法将“Null”类型的值分配给 const 构造函数中“String”类型的参数

无法将类型为'HttpEvent <any>'的角形参数分配给该参数

“any[]”类型的参数不能分配给“string”类型的参数

无法将类型Observable <Observable <any [] >>分配给类型Observable <any []>

Angular中无法将类型“ Promise <any>”分配给类型“ any []”的错误

类型“ any”的参数不能分配给“ never”类型

在函数返回中使用泛型类型类型“any[]”不可分配给类型“T”

ionic 2“类型'{}'无法分配给类型'any []”

类型'MonoTypeOperatorFunction <any>'的参数不能分配给类型'UnaryFunction <Observable <any>,Observable <any >>'的参数

Swift:无法将类型“ Any”的值分配给类型“ AnyObject”的值?

Angular TypeScript错误-无法将类型'number'分配给类型'any []'

无法将类型“[String]”的值分配给类型“[[String : Any]]”

如何将json响应传递给函数:类型'unknown'的参数不能分配给类型'any []'的参数

Angular-无法将响应分配给'request?类型:HttpRequest <any>

类型'Function'的参数不能分配给类型'(... args:any [])=> void'的参数

“any”类型的参数不可分配给“never”类型的参数 - 数组已传递

ts(2345)类型'any'的参数不能分配给'never'类型的参数

Angular 6-参数类型订阅不能分配给参数类型Array <any>

类型'Element'的参数不能分配给'ReactElement <any>类型的参数

typescript:类型“ any []”的参数不能分配给类型“ []”的参数。ts(2345)

'Promise <any>'类型的参数不能分配给'string'类型的参数

类型“ any”的参数不能分配给“从不”类型的参数打字稿解决方案

“HTMLFormElement”类型的参数不可分配给“ElementRef<any>”类型的参数

为什么push显示类型'any []'的参数不能分配给'never'类型的参数错误?

Redux-createStore。类型的参数不能分配给类型'DeepPartial <any>'的参数

'Promise<any[]>' 类型的参数不可分配给 'readonly unknown[] 类型的参数

在Angular 4.x应用程序中,无法将类型“对象”分配给类型“ any []”

Angular-如何解决“错误TS2322:类型'ModuleWithProviders <any>'无法分配给类型'any [] |类型<any>'”

“any[]”类型的参数不可分配给“PollModel”类型的参数。“any[]”类型中缺少属性“pollId”