假设我有一些数组类型T[],是否可以T在另一个别名/接口中提取类型?例如,我的(假的)理想代码如下:
// for illustration only...
type ArrayElement<T[]> = T;
// then, ArrayElement<string[]> === string
Run Code Online (Sandbox Code Playgroud)
如果不是,是否存在不允许此类运营商的一般类型理论原因?如果没有,我可能会建议添加它.
谢谢!
// from a library
type T = null | "auto" | "text0" | "text1" | "text2" | "text3" | "text4";
//in my code
type N = Extract<T, `text${number}`> extends `text${infer R}` ? R : never
Run Code Online (Sandbox Code Playgroud)
(TS游乐场)
对于上面的代码段N将相当于"0" | "1" | "2" | "3" | "4". 我怎样才能将其转换为数字类型,即0 | 1 | 2 | 3 | 4?已经尝试 & number在某些地方放置,例如infer R & number,但都不起作用。
我正在使用Typescript创建一个shogi游戏板.将棋盘有9个等级和档案.
我想断言一个9x9多维数组作为一种类型,以确保数组的大小和内容.
目前我正在以这种方式创建我的9x9板类型:
type Board9x9<P> = [
[P, P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P, P],
[P, …Run Code Online (Sandbox Code Playgroud) 给定一个 TypeScript 元组,例如:
const arr = [1, 2] as const;
Run Code Online (Sandbox Code Playgroud)
我们对索引进行静态类型检查:
console.log(arr[1]);
Run Code Online (Sandbox Code Playgroud)
很好,但是
console.log(arr[2]);
Run Code Online (Sandbox Code Playgroud)
错误:
长度为“2”的元组类型“readonly [1, 2]”在索引“2”处没有元素。ts (2493)
这太棒了。
我想声明一个常量为该元组索引的类型,以便分配给该常量的内容遵循相同的约束(0 | 1)。
我试过这个:
const index: keyof typeof arr = 2 as const;
console.log(arr[index]);
Run Code Online (Sandbox Code Playgroud)
但 TypeScript 没有显示任何错误。我怀疑这个index范围number太宽泛了。
When using generics in TypeScript, you sometimes see a type Parameter such as:
T extends string
Run Code Online (Sandbox Code Playgroud)
Isn’t this the same as using string directly? Can you subclass string? What would this be good for?