how to define static constants in typescript and angular how to define static constants in typescript and angular angular angular

how to define static constants in typescript and angular


Define an abstract class for your constants:

export abstract class Constants {  static readonly STUDENT_NAMES: string[] = ["JOHN", "BOB", "NICK"];  static readonly TEACHER_NAME: string[] = ["HARRY", "CHRIS"];  static readonly SCHOOL_CODE: number[] = [100, 102, 107];}

Then include this class whereever needed with import { Constants } from '...'; and use its values with const names: string[] = Constants.STUDENT_NAMES;

Regarding the naming I agree with @AdrianBrand to prefer names like studentNames, teacherNames and schoolCodes.

Edit: TypeScript 3.4 introduced so called const assertions, which might also be suited:

export const constants = {  studentNames: ["JOHN", "BOB", "NICK"],  ...} as const;


You put them in a TypeScript file and import them where needed.

export const STUDENT_NAMES: string[] = ["JOHN","BOB","NICK"];

Put it in student-names.ts

import { STUDENT_NAMES } from './path/cosnstants/student-names';

where you need it.

Personally I would name them studentNames and not STUDENT_NAMES but that is a matter of taste.


You can create a TS file constants.ts that contains all your constants :

export const constants = {   STUDENT_NAMES: ["JOHN","BOB","NICK"],   TEACHER_NAME: ["HARRY","CHRIS"],   SCHOOL_CODE: [100,102,107]};

Then whenever you need a constant you can call it like this code bellow:

let studentsNames : any = constants.STUDENT_NAMES;

Regards,