Typescript检查输入必填字段的类型字段是否为可选字段



我想检查typescript类型或接口的字段是否是可选的。

export type Recommendation = {
id?: string,
name: string,
type?: string,
tt: string,
isin?: string,
issuer: string,
quantity?: number,
recDate: string,
createDate: string,
buyPrice?: number,
currentPrice?: number,
performance?: number,
comment?: string,
updateDate?: string,
updateRec?: string,
recentRec?: string,
}

例如名称和颁发者不是可选的,大多数其他字段都是可选的。

我现在已经创建了(用于提交表单的(动态输入字段;"必需";属性,具体取决于是否需要Recommendation类型的类型。。

<Table responsive>
<thead>
<tr>
<th>#</th>
<th colSpan={10}>Create new data</th>
</tr>
</thead>

<tbody>
<tr>
<td>1</td>
{Array.from(Object.keys(sr)).map((colName, index) => (
<td key={index}><input required={ checkRequired ? true : false} name={colName} style={{width: "150px"}} type="text" placeholder={JSON.stringify(colName)} onChange={e => setFieldObj(e)} value={inputValue[colName]}></input></td>
))}
</tr>
</tbody>
</Table>
<button onClick={submitNewRecord}>Submit</button>

如何使用typescript类型执行required={ checkRequired ? true : false}

正如@AlekseyL在评论中提到的那样,您无法在运行时访问类型信息。但是,在某些情况下,您可以在编译时访问数据。

如果您将类型拆分为一个包含必需字段的const数组,以及一个没有任何字段可选的类型:

export const RequiredFields = ['name', 'tt', 'issuer', 'recDate', 'createDate'] as const;
type RecommendationFields = {
id: string,
name: string,
type: string,
tt: string,
isin: string,
issuer: string,
quantity: number,
recDate: string,
createDate: string,
buyPrice: number,
currentPrice: number,
performance: number,
comment: string,
updateDate: string,
updateRec: string,
recentRec: string,
};

您可以使用该信息重建Recommendation:

type OptionalFields = Exclude<keyof RecommendationFields, typeof RequiredFields[number]>;
type RecommendationOptional = { [key in OptionalFields]?: RecommendationFields[key] };
type RecommendationRequired = { [key in typeof RequiredFields[number]]: RecommendationFields[key] };
export type Recommendation = RecommendationOptional & RecommendationRequired;

然后在运行时,您可以通过检查数组来测试字段是否是可选的:

function isFieldRequired(name: string) {
return RequiredFields.includes(name);
}

相关内容

  • 没有找到相关文章

最新更新