Reputation: 43
I'm new to TypeScript, and working one of my company's repos that uses it heavily. (We're building a React/Redux app.) I'm familiar with the basic concept of TypeScript Generics, but a particular bit of syntax is befuddling. Here's an example of the code in question (it's in a reducer):
interface EntityState<Entity> {
entity?: Entity;
status: ApiStatus; // enum
}
interface FieldSummary {
dataType?: string;
// other properties...
}
function singleField(state: EntityState<FieldSummary> = defaultEntityState,
action: ActionTypes) {...}
Would someone be able to explain what EntityState<FieldSummary>
is doing? If further details are needed just let me know.
Upvotes: 2
Views: 167
Reputation: 250812
It's an example of a generic type argument.
interface EntityState<Entity> {
entity?: Entity;
status: ApiStatus;
}
The interface will contain an optional entity?
of a type to be defined later. For now, it has been called Entity
.
When you use this interface, you supply the type, thus:
const stringEntity: EntityState<string>;
The property stringEntity.entity
will either be a string
or undefined
(given it is optional).
const numEntity: EntityState<number>;
The property numEntity.entity
will either be a number
or undefined
.
And so on. The type argument you supply when you use the interface can be any type that satisfies any constraints - in your case, the type parameter is unconstrained. It means you can re-use an interface because the type is defined later.
Upvotes: 3