Reputation: 965
Let say I'm defining model Person
export class Person {
public firstName: string;
public lastName: string;
public gender: ???;
}
I want gender to be either 'Male' or 'Female'.
I guess I have to create anther class (in same model or separate??).
export class Gender {
public id: number;
public name: string;
}
and construct values [{0: "Male"},{1: "Female"}]
Is this the right way to do it? If yes how do I define that Gender type in Person model?
Upvotes: 2
Views: 326
Reputation: 640
You could use enum
export enum Gender{
Male,
Female,
Other
}
export class Person {
public firstName: string;
public lastName: string;
public gender: Gender;
}
Upvotes: 0
Reputation: 447
First of all in Typescript use interfaces instead of classes for models with only attributes in them. Use classes only when you want a constructor and define methods that do computational work.
There are 3 ways to solve your problem, you can either use an interface in the same you you mentioned, or you can define Gender as an enum
, or you do this:
export interface Person {
public firstName: string;
public lastName: string;
public gender: 'Male' | 'Female';
}
Upvotes: 2
Reputation: 1197
You can either go your class way, then define it like this:
export class Person {
public firstName: string;
public lastName: string;
public gender: Gender;
}
or, use strings:
export class Person {
public firstName: string;
public lastName: string;
public gender: "Male" | "Female";
}
That way you do not need another class.
Upvotes: 1
Reputation: 38683
Use boolean
type
public gender: boolean;
If gender
value is true means male else female. That's it
Upvotes: 0