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

时间:2016-11-15 05:40:12

标签: arrays typescript types interface nested

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

例如,让我们说我正在编写一个函数来测试针对任意数量模式的路径。

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

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']]]);

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

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!!!

有没有办法在TypeScript中实现这个目的?

1 个答案:

答案 0 :(得分:6)

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

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

interface DeepArray<T> extends Array<T | DeepArray<T>> { }

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

type Matcher = DeepArray<string | RegExp>;

const m1: Matcher = ['src/**/*', /\.js$/];
const m2: Matcher = ['src/**/*', [/\.js$/, ['*.ts']]];

但是问题指出该函数还应该接受单个stringRegExp。这个 仍会产生编译错误。

const m3: Matcher = 'lib/**/*';         // Compiler Error!!!
const m4: Matcher = /\/node_modules\//; // Compiler Error!!!

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

type Deep<T> = T | DeepArray<T>;

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

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!!!