本文介绍了在TypeScript中描述一个深层嵌套的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I define a type or interface describing a deeply nested array in TypeScript?

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

For example, let's say I am writing a function for testing a path against any number of patterns.

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

Matcher类型可以是以下任意一种:

The Matcher type may be any of the following:

  • string
  • RegExp
  • Matcher[](请注意自引用)
  • string
  • RegExp
  • Matcher[] (note the self-reference)

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

In other words, the compiler should accept the following:

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

但是以下内容会产生编译器错误:

But the following should produce a compiler error:

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中实现?

Is there a way to achieve this in TypeScript?

推荐答案

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

Yes, you can do this in TypeScript. The solution is a bit verbose, but it can be done using acombination of generic type aliases and interfaces.

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

Start with an interface defining a deeply nested array.

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

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

So far, the compiler will accept the following:

type Matcher = DeepArray<string | RegExp>;

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

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

But the question specifies that the function should also accept a single string or RegExp. Thiswill still produce a compiler error.

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

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

We can solve this problem with a generic type alias:

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

现在我们的类型可以正常工作了.

And now our type works as expected.

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

这篇关于在TypeScript中描述一个深层嵌套的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 13:50