I need to determine whether the fields of a typescript type or interface are optional or required.
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,
}
For instance, "name" and "issuer" are required, while most other fields are optional.
I have created dynamic input fields for a submit form and I want to dynamically set the "required" attribute on those inputs based on the requirements of the Recommendation type.
<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={Recommendation.hasOwnProperty(colName)} 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>
Is there a way to achieve this using typescript?