How to Specify that a Class Property is an Integer in TypeScript ?
Last Updated :
17 Jan, 2024
Specifying that a class property is an integer in TypeScript involves using type annotations or specific TypeScript features to define the data type of the property.
Below are the approaches used to specify that a class property is an integer in TypeScript:
Approach 1: By using Type Annotation
Type annotation involves explicitly stating the data type of a variable or property.
Example: Here, we use the : number
type annotation to specify that myIntegerProperty
should be of type number. We create an instance of MyClass
and log the value myIntegerProperty
to the console.
Javascript
class MyClass {
myIntegerProperty: number;
constructor(value: number) {
this .myIntegerProperty = value;
}
}
const myInstance = new MyClass(5);
console.log(myInstance.myIntegerProperty);
|
Output:
5
Approach 2: By using Number Type Literal
Using number literal types allows you to specify a property to have a specific numeric value.
Example: Here, we use the number literal 42
to specify that myIntegerProperty
should have the value 42. When creating an instance, we ensure that the property is assigned the correct value.
Javascript
class MyClass {
myIntegerProperty: 42;
constructor() {
this .myIntegerProperty = 42;
}
}
const myInstance = new MyClass();
console.log(myInstance.myIntegerProperty);
|
Output:
42
Approach 3: By using Enum
Enums are used to create a set of named constant values. They can be employed to restrict a property to a predefined set of integer values.
Example: We define an enum IntegerValues
with specific integer values. The class property myIntegerProperty
is then restricted to these enum values, ensuring it can only be assigned one of them.
Javascript
enum IntegerValues {
MyInteger = 42,
AnotherInteger = 7,
}
class MyClass {
myIntegerProperty: IntegerValues;
constructor(value: IntegerValues) {
this .myIntegerProperty = value;
}
}
const myInstance = new MyClass(IntegerValues.MyInteger);
console.log(myInstance.myIntegerProperty);
|
Output:
42
Approach 4: By using Type Alias
Type aliases allow you to create custom names for types, providing a semantic way to define integer types.
Example: Using a type alias (Integer
), we create a custom type for integers. The class property myIntegerProperty
is then annotated with this custom type, providing clarity and reusability.
Javascript
type Integer = number;
class MyClass {
myIntegerProperty: Integer;
constructor(value: Integer) {
this .myIntegerProperty = value;
}
}
const myInstance = new MyClass(10);
console.log(myInstance.myIntegerProperty);
|
Output:
10
Share your thoughts in the comments
Please Login to comment...