【问题标题】:Typescript check if type field is optional or not for input required fields打字稿检查类型字段是否对于输入必填字段是可选的
【发布时间】:2022-01-08 00:47:54
【问题描述】:

我想检查 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,
}

例如 name 和 issuer 不是可选的,大多数其他字段都是。

我现在创建了动态输入字段(用于提交表单),我想根据 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>

required={ checkRequired ? true : false} 用 typescript 类型怎么办?

【问题讨论】:

  • 不能,运行时类型信息不可用。

标签: typescript forms validation input required


【解决方案1】:

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

如果你将你的类型拆分为一个由必填字段组成的 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    相关资源
    最近更新 更多