在TypeScript中描述一个深度嵌套的数组

McM*_*ath 7 arrays types nested interface typescript

如何在TypeScript中定义描述深层嵌套数组的类型或接口?

例如,假设我正在编写一个函数来测试针对任意数量模式的路径.

function match(path: string, matcher: Matcher): boolean { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

Matcher类型可以是任何以下的:

  • string
  • RegExp
  • Matcher[] (注意自我引用)

换句话说,编译器应该接受以下内容:

match('src/index.js', 'lib/**/*');
match('src/index.js', /\/node_modules\//);
match('src/index.js', ['src/**/*', /\.js$/]);
match('src/index.js', ['src/**/*', [/\.js$/, ['*.ts']]]);
Run Code Online (Sandbox Code Playgroud)

但是以下应该会产生编译器错误:

match('src/index.js', {'0': 'src/**/*'});               // Compiler Error!!!
match('src/index.js', ['src/**/*', true]);              // Compiler Error!!!
match('src/index.js', ['src/**/*', [/\.js$/, [3.14]]]); // Compiler Error!!!
Run Code Online (Sandbox Code Playgroud)

有没有办法在TypeScript中实现这一目标?

McM*_*ath 7

是的,您可以在TypeScript中执行此操作.解决方案有点冗长,但可以使用通用类型别名和接口的组合来完成.

从定义深层嵌套数组的接口开始.

interface DeepArray<T> extends Array<T | DeepArray<T>> { }
Run Code Online (Sandbox Code Playgroud)

到目前为止,编译器将接受以下内容:

type Matcher = DeepArray<string | RegExp>;

const m1: Matcher = ['src/**/*', /\.js$/];
const m2: Matcher = ['src/**/*', [/\.js$/, ['*.ts']]];
Run Code Online (Sandbox Code Playgroud)

但问题是该函数还应该接受单个stringRegExp.这仍然会产生编译器错误.

const m3: Matcher = 'lib/**/*';         // Compiler Error!!!
const m4: Matcher = /\/node_modules\//; // Compiler Error!!!
Run Code Online (Sandbox Code Playgroud)

我们可以使用泛型类别别名解决此问题:

type Deep<T> = T | DeepArray<T>;
Run Code Online (Sandbox Code Playgroud)

现在我们的类型按预期工作.

type Matcher = Deep<string | RegExp>;

function match(path: string, matcher: Matcher): boolean { /* ... */ }

match('src/index.js', 'lib/**/*');
match('src/index.js', /\/node_modules\//);
match('src/index.js', ['src/**/*', /\.js$/]);
match('src/index.js', ['src/**/*', [/\.js$/, ['*.ts']]]);

match('src/index.js', {'0': 'src/**/*'});                 // Compiler Error!!!
match('src/index.js', ['src/**/*', true]);                // Compiler Error!!!
match('src/index.js', ['src/**/*', [/\.js$/, [3.14]]]);   // Compiler Error!!!
Run Code Online (Sandbox Code Playgroud)