gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:37:40 24 4
gpt4 key购买 nike

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

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

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

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

  • 字符串
  • 正则表达式
  • 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 中实现这一点?

最佳答案

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

从定义深度嵌套数组的接口(interface)开始。

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

关于arrays - 在 TypeScript 中描述一个深度嵌套的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40602784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com