Reputation: 149
I have a class DropdownItem which creates a blueprint for a dropdown option.
class DropdownItem {
value: string;
name: string;
....
}
Is there any other option that just naming it DropdownItemInterface.?
interface DropdownItemInterface { // ???
value: string;
name: string;
}
What is the best practice, or is there one?
Upvotes: 0
Views: 250
Reputation: 1075209
The convention is to just use the class name as the type. As in most (but not all) languages with classes, the class defines both the implemenation and the interface. You can define a separate interface, but it's not required and standard practice is not to do so.
Note that in TypeScript, things are assignment-compatible even if they don't have a type relationship via declared interfaces. For instance:
class DropdownItem {
value: string = "";
name: string = "";
}
function example(item: DropdownItem): void {
//...
}
const item1 = {value: "x", name: "foo"};
example(item1); // No error here, even though `item1` is not
// declared of type DropdownItem
In fact, what you use as a DropdownItem
only has to have value
and name
with the right types, even if it has other things as well:
const item2 = {value: "y", name: "bar", other: 42};
example(item2); // No error here, it's okay that it has an
// extra property
If you do decide to have a separate interface, I don't think there's any one standard way of naming the interface. Most interfaces I've seen in TypeScript are just named in the normal way, without any particular indicator that they're interfaces. On those rare occasions when an indicator is used, it's typically an I
prefix, e.g. IDropDownItem
, but I suspect I've mostly seen that in code written by people used to it from other languages or (showing my age) COM.
Upvotes: 4