TypeScript does not have a built-in integer type, but you can still restrict or represent integer-like values using various TypeScript features.
- All numbers in TypeScript are floating-point (number type).
- Integer-only enforcement requires custom checks or constraints.
Below are simple approaches to define numeric or controlled integer-style properties in a class.
Table of Content
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.
class MyClass {
myIntegerProperty: number;
constructor(value: number) {
this.myIntegerProperty = value;
}
}
const myInstance = new MyClass(5);
console.log(myInstance.myIntegerProperty);
Output:
5Approach 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.
class MyClass {
myIntegerProperty: 42;
constructor() {
this.myIntegerProperty = 42;
}
}
const myInstance = new MyClass();
console.log(myInstance.myIntegerProperty);
Output:
42Approach 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.
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:
42Approach 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.
type Integer = number;
class MyClass {
myIntegerProperty: Integer;
constructor(value: Integer) {
this.myIntegerProperty = value;
}
}
const myInstance = new MyClass(10);
console.log(myInstance.myIntegerProperty);
Output:
10