相关疑难解决方法(0)

Typescript从元组/数组值派生联合类型

说我有清单 const list = ['a', 'b', 'c']

是不是可以从这个值的联合类型派生出来的'a' | 'b' | 'c'

我想要这个,因为我想定义只允许来自静态数组的值的类型.而且我还需要在运行时枚举这些值,所以我使用数组.

示例如何使用索引对象实现:

const list = ['a', 'b', 'c']

'a' | 'b' | 'c'

const list = ['a', 'b', 'c']

但我想知道没有这个索引地图是否可行.

typescript

46
推荐指数
3
解决办法
7956
查看次数

TypeScript数组到字符串文字类型

我目前有一个字符串数组和一个包含相同字符串的字符串文字联合类型:

const furniture = ['chair', 'table', 'lamp'];
type Furniture = 'chair' | 'table' | 'lamp';
Run Code Online (Sandbox Code Playgroud)

我在我的应用程序中需要两个,但我试图保持我的代码DRY.那么有没有办法从另一个推断出一个?

我基本上想说些什么type Furniture = [any string in furniture array],所以没有重复的字符串.

arrays string types typescript

26
推荐指数
3
解决办法
6471
查看次数

“只读...”类型的参数不可分配给“...[]”类型的参数

有一个类似的问题,但与我在这里发现的问题不同,类型为“...”的参数不能分配给类型为“...”的参数 TS 2345

utils.ts(https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types

export function getRandomItem<T>(array: T[]): T {
  return array[Math.floor(Math.random() * array.length)]
}
Run Code Online (Sandbox Code Playgroud)

服装.ts

import { getRandomItem } from "@/assets/ts/utils"

export const apparelLocation = ["HEAD", "TORSO", "ARMS", "LEGS"] as const
export type TypeApparelLocation = typeof apparelLocation[number]

// ...

export class Apparel {
  / ...
  location: TypeApparelLocation

  constructor(rating: number) {
    // ...
    this.location = getRandomItem(apparelLocation)
    }
  }
Run Code Online (Sandbox Code Playgroud)

使用的时候会报错getRandomItem()

Argument of type 'readonly ["HEAD", "TORSO", "ARMS", "LEGS"]' is not assignable to parameter of type '("HEAD" | …

arrays typescript

16
推荐指数
1
解决办法
2万
查看次数

标签 统计

typescript ×3

arrays ×2

string ×1

types ×1