Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define static constants in typescript and angular

Tags:

I have bunch of constants which are business related and I have to store them in Angular.Something like below

STUDENT_NAMES= ["JOHN","BOB","NICK"] TEACHER_NAME = ["HARRY","CHRIS"]  SCHOOL_CODE = [100,102,107]; 

I have a lot of them and they are kind of static ..I need them in most of my service classes. What is the best place to store them? Should i create a interface and let my service class inherit them? In java , we define a class of public static final constants and other classes uses them.Like this , what is the typescript way?

like image 937
Janier Avatar asked Nov 05 '18 23:11

Janier


People also ask

How do I create a static variable in TypeScript?

TypeScript will generate the following JavaScript code for the above Circle class. var Circle = /** @class */ (function () { function Circle() { } Circle. pi = 3.14; return Circle; }()); The following example defines a class with static property and method and how to access it.

How do you define a constant in a TypeScript class?

Use the readonly modifier to declare constants in a class. When a class field is prefixed with the readonly modifier, you can only assign a value to the property inside of the classes' constructor. Assignment to the property outside of the constructor causes an error.

How do I store a constant in TypeScript?

Use Class with static properties One way to manage constants in TypeScript is to use the class. In the following example, the AppSettings class is created with static properties to define constants. Those properties are applied with readonly modifiers, thus they can not be reassigned.


1 Answers

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; 
like image 141
pzaenger Avatar answered Sep 18 '22 08:09

pzaenger