相关疑难解决方法(0)

TypeScript:从字符串数组中定义联合类型

我不能成为遇到这个问题的第一个人,但我的搜索还没有发现任何有用的线索.非常感谢一些专家的TypeScript建议.

说我有一个数组:

const fruits = ["Apple", "Orange", "Pear"];
Run Code Online (Sandbox Code Playgroud)

我想定义一个对象,将每个水果映射到一些有趣的事实:

interface Facts {
    color: string,
    typicalWeight: number
}

const fruitFacts: { [key: members of fruits]: Facts } = {
    "Apple": { color: "green", typicalWeight: 150 }
    //
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做[key: members of fruits]

额外:我如何强制我的fruitFacts对象耗尽从数组派生的所有键,以便它在上面的例子中指定苹果,橘子和梨的事实.

typescript

17
推荐指数
2
解决办法
3165
查看次数

特定字符串值的打字稿数组

我有一个数组

const relations = ['profiles', 'locations', 'change_history']
Run Code Online (Sandbox Code Playgroud)

如果我想创建一个像

interface IParams {
  id: number;
  relations: []string; // how to make this an array of those relations above?
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

typescript

7
推荐指数
3
解决办法
3250
查看次数

强制数组在联合类型上是详尽的

给定一个使用此处描述的技术创建的强类型元组:

const tuple = <T extends string[]>(...args: T) => args;
const furniture = tuple('chair', 'table', 'lamp');

// typeof furniture[number] === 'chair' | 'table' | 'lamp'
Run Code Online (Sandbox Code Playgroud)

我想在设计时断言它对另一种联合类型是详尽无遗的:

type Furniture = 'chair' | 'table' | 'lamp' | 'ottoman'
Run Code Online (Sandbox Code Playgroud)

我如何创建一个类型来确保furniture包含联合中的每个类型Furniture

目标是能够在设计时像这样创建一个数组,如果它失败应该Furniture改变;理想的语法可能如下所示:

const furniture = tuple<Furniture>('chair', 'table', 'lamp')
Run Code Online (Sandbox Code Playgroud)

typescript

6
推荐指数
1
解决办法
586
查看次数

打字稿:检查类型中是否包含值

我对定义的类型有疑问,并检查该类型中是否包含值。

这是我的示例:

这些类型是:

export type Key = 'features' | 'special';

export type TabTypes = 'info' | 'features' | 'special' | 'stars';
Run Code Online (Sandbox Code Playgroud)

当用户更改选项卡时,它会从Type of TabTypes发送一个字符串值。

activeTabChanged(event: TabTypes) {
    this.activeTab: TabTypes = event;
    // it won't let me set the key here because key has a different type 
    // but the send event can be contained in type Key
    // how can I check if the send event from type TabTypes is contained in type Key
    this.key: Key = event;
}
Run Code Online (Sandbox Code Playgroud)

有没有一种打字稿方法来检查带有类型的发送值是否可以等于来自其他类型的值?

types typescript angular

5
推荐指数
2
解决办法
4113
查看次数

TS:如何获取常量数组元素类型

我将 TS 3.4.5 与 const 断言一起使用。如何检索声明的常量数组变量的元素类型?

export type GetArrayElementType<T extends Array<any>> = T extends (infer U)[] ? U : never;

export const MyConstArray = [
  'item1',
  'item2',
  'item3',
] as const;

export type MyConstArrayItem = GetArrayElementType<typeof MyConstArray>;
Run Code Online (Sandbox Code Playgroud)

我想有作为输出:

export type MyConstArrayItem = "item1" | "item2" | "item3"
Run Code Online (Sandbox Code Playgroud)

我不完全确定如何提取项目的类型信息,因为由于 const 断言,我的数组不再是数组类型而是一个常量元组,因此GetArrayElementType不能对其应用。

typescript

4
推荐指数
2
解决办法
2183
查看次数

标签 统计

typescript ×5

angular ×1

types ×1