我正在开发一个纯终端库,它重写了打字版的jQuery终端.
我有这样的代码:
type Effect = 'g' | 'b' | 'i' | 'u' | 's' | 'o';
type NotEffect = `-${Effect}`;
type Item = '!' | '@';
type Effects = Array<Effect | NotEffect | Item>;
type Stack = Array<string>;
type Style = {[key: string]: string};
type Attrs = {[key: string]: string} & {style?: Style};
type Formating = [
Effects,
string,
string,
Array<string> | undefined,
string | undefined,
Attrs | undefined
];
const output: Formating = [[], '', '', undefined, undefined, undefined];
将未定义添加到格式设置是一种解决方法,用于修复元素长度不同的UNION类型的问题,该问题是导致该问题的原因:
type Formating = [Effects, string, string]
| [Effects, string, string, Array<string>]
| [Effects, string, string, Array<string>, string]
| [Effects, string, string, Array<string>, string, Attrs]
当我想要设置格式的第4个元素和下一个元素时,添加此类型会出错.添加未定义解决了类型脚本的问题,但它改变了Java代码的行为.我需要添加黑客来解决格式具有未定义的值的问题.
有没有一种方法可以形成一个元素数量可变的元组?
编辑
这是我真正的代码:
const class_i = 3; // index of the class in formatting
const attrs_i = 5; // index of attributes in formattings
function get_inherit_style(stack: Stack) {
const output: Formating = [[], '', ''];
function update_attrs(value: string) {
if (!output[attrs_i]) {
output[attrs_i] = {};
}
try {
const new_attrs = JSON.parse(value);
if (new_attrs.style) {
const new_style = new_attrs.style;
const old_style = output[attrs_i].style;
output[attrs_i] = {
...new_attrs,
...output[attrs_i],
...{
style: update_style(new_style, old_style)
}
};
} else {
output[attrs_i] = {
...new_attrs,
...output[attrs_i]
};
}
} catch (e) {
warn('Invalid JSON ' + value);
}
}
if (!stack.length) {
return output;
}
for (let i = stack.length; i--;) {
let formatting = parse_formatting(stack[i]);
if (formatting.length > 5) {
const last = formatting.slice(5).join(';');
formatting = formatting.slice(0, 5).concat(last);
}
const style = formatting[0].split(/(-?[@!gbiuso])/g).filter(Boolean);
style.forEach(function(s) {
if (is_valid_effect(s) && output[0].indexOf(s) === -1) {
output[0].push(s);
}
});
for (let j = 1; j < formatting.length; ++j) {
const value = formatting[j].trim();
if (value) {
if (j === class_i) {
if (!output[class_i]) {
output[class_i] = [];
}
const classes = value.split(/\s+/);
output[class_i] = output[class_i].concat(classes);
} else if (j === attrs_i) {
update_attrs(value);
} else if (!output[j]) {
output[j] = value;
}
}
}
}
return stringify_formatting(output);
}
我有一个错误:
长度为"%3"的元组类型"[Effects,字符串,字符串]"在索引"%3"处没有元素
当访问output[class_i]
时