Reputation: 890
Suppose I have an interface called ISeminar
export interface ISeminar {
id: number;
title: string;
description: string;
registrationStartDate: any;
registrationEndDate: any;
seminarStartTime?: any;
seminarEndTime?: any;
companyList?: any;
status?: Status;
}
I can create a new type for my control object by using
controls: { [key in keyof ISeminar] : FormControl};
But here, all the keys of the interface are compulsory. I want to keep to keys which are optional in the interface, optional in the control object.
Upvotes: 2
Views: 643
Reputation: 4820
Note that TypeScript by default won't compile interfaces at all unless it needs to. And if it does (like in your case), it will compile it to plain old javascript object. And in javascript there is no notion of "optional" fields.
If you really need to create FormControls
out of your interface, I guess your best bet is to have two interfaces, e.g.
export interface IBaseSeminar {
id: number;
title: string;
description: string;
registrationStartDate: any;
registrationEndDate: any;
}
and some extended interface, e.g.
export interface IScheduledSeminar extends IBaseSeminar {
seminarStartTime?: any;
seminarEndTime?: any;
companyList?: any;
status?: Status;
}
Then you can iterate the keys of the base class, and use the extended one in cases when you need to.
But personally I wouldn't go out of my way to change the models / interfaces just to iterate their keys like this (unless this actually fits the domain of your application).
Upvotes: 2