我想檢查打字稿型別或介面的欄位是否是可選的(或不是)。
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}處理打字稿型別?
uj5u.com熱心網友回復:
正如評論中提到的@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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370693.html
