我有如下代码
export type ConditionalItemType = [
{ condition: string },
{ [key: string]: FormItemDataType }
];
export type ConditionalItemDataType = ConditionalItemType[];
export type FormItemDataType = {
required: boolean;
type: string;
constraint?: TextConstraintType;
options?: string[];
conditional?: ConditionalItemDataType;
};
export type TextConstraintType = {
min?: number;
max?: number;
format?: string;
};
const obj: FormItemDataType = {
required: true,
type: 'select',
options: ['simple', 'complicated'],
conditional: [
[
{ condition: 'complicated' },
{
'How Complicated': {
required: true,
type: 'text',
constraint: {
max: 30,
},
},
},
],
],
};
const func = (input: FormItemDataType) => {
if ('conditional' in input) {
input.conditional.filter((arrItem) => console.log(arrItem));
} else null;
};
我得到了
'input.conditional' is possibly 'undefined'
错误在
input.conditional.filter((arrItem) => console.log(arrItem))
。
如何消除这个错误?我不能使用
non-null assertion
或
optional chaining
。我也不能更改类型。
我想我可以通过使用“Type Guards”&我想我是在
if ('conditional' in input)
但显然不是。有人能帮忙吗?
使现代化