Home > other >  How do I define a range of allowed values for a property in typescript?
How do I define a range of allowed values for a property in typescript?

Time:01-01

In angular, is there anyway to create a data model that has a field of categories?

example: I am making a job application app. each job can have multiple category types such as electrical, plumbing etc.

right now this is what my code for the data model looks like. I would like to lock in the state, substate and jobType. but I don't know how to do it

export interface Job {
    id: string;
    content: string;
    imagePath: string;
    creator: string;
    state: string;
    substate: string;
    jobType: string[];   
    address: string;
}

export const STATES = ['new','open','pending','closed']
export const SUBSTATES = ['new','cancelled','closed complete','closed incomplete']
export const JOBTYPES = ['Handyman', 'Landscape', 'Plumming', 'Remodeling', 'Roofing', 'Electrical'];

if it is not possible, do you recommend storing the choices in another file? I read somewhere that having a const folder is considered best practices but I am new at angular so idk what I am doing.

thank you!

CodePudding user response:

If I understand you correctly, you want certain properties of your model to have only a limited range of possible values. You can achieve this as follows:

export interface Job {
    id: string;
    content: string;
    imagePath: string;
    creator: string;
    state: JobState;
    substate: SubState;
    jobType: JobType[];   
    address: string;
}

export type JobState = 'new' | 'open' | 'pending' | 'closed';
export type SubState = 'new' |'cancelled'|'closed complete'|'closed incomplete';
export type JobType = 'Handyman' | 'Landscape' | 'Plumming' | 'Remodeling' | 'Roofing' | 'Electrical';

So if for example you want to create a new Job-object containing the property state, intellisense will detect if the assigned value corresponds to one of the allowed choices. So you will get intellisense-support and at the same time you can still work with string-values, as you can see in the example below.

Regarding the above mentioned sample model, the following rules apply:

const job = { state: 'new' } as Job; // will be detected as valid

const job = { state: 'Hello World' } as Job; // will be detected as INVALID

CodePudding user response:

You could use enumeration.

For example:

export enum JobState {
  New = 'new',
  Open = 'open',
  Pending = 'pending',
  Closed = 'closed'
}
export interface Job {
    id: string;
    content: string;
    imagePath: string;
    creator: string;
    state: JobState;
    ...
}
  • Related