考虑以下示例:
class A {
private constructor(public n: number) {}
public getDouble() {
return this.n * 2;
}
static from(s: string): A;
static from(n: number): A;
static from(n1: number, n2: number): A;
static from(...args: unknown[]): A {
if (args.length === 1) {
if (typeof args[0] === 'string') {
if (args[0].length !== 1) {
throw new Error('String must have a length of 1')
}
return new A(Number(args[0]));
} else if (typeof args[0] === 'number') {
if (args[0] > 9) {
throw new …
Run Code Online (Sandbox Code Playgroud) 我有一个通用函数,我想让它只接受固定长度(可能是混合类型)元组作为类型参数。我事先不知道可能的元组类型 - 它应该接受任何固定长度的元组。
doSomething<[number, string, boolean]>(); // this should be okay
doSomething<number[]>(); // this should throw a compiler error
Run Code Online (Sandbox Code Playgroud)
我知道我可以将长度限制为特定的数字文字(为简洁起见,省略数组检查):
type LengthOf<N extends number> = {
length: N;
}
function doSomething<T extends LengthOf<2>(){};
doSomething<[any, any]>(); // ok
doSomething<[any]>(); // error
Run Code Online (Sandbox Code Playgroud)
但我不能使用此方法将长度限制为任何数字文字,因为任何数字文字都会扩展数字,这也是length
可变长度数组的类型。
这在 TypeScript 中可能吗?