DataType in TypeScript
DataType in TypeScript
A data type is a classification that specifies which type of value a variable can
hold. It helps TypeScript understand and manage the different kinds of data in your
program.
When you define a variable in TypeScript, you can specify its data type to
ensure that it holds the right kind of value. This helps catch errors early. Example of
different data type are given below.
number
Represents numeric values.
//number
//Represents numeric values.
let age:number =25;
let marks:number = 92.5;
console.log(age)
// Check the data type of 'age'
let ageType: string = typeof age;
console.log(`The data type of 'age' is: ${ageType}`);
console.log(marks)
// Check the data type of 'marks'
let marksType: string = typeof marks;
console.log(`The data type of 'marks' is: ${marksType}`);
string
Represents textual data.
//string
//Represents textual data.
console.log(stdAdd)
// Check the data type of 'stdAdd'
let stdAddType: string = typeof stdAdd;
console.log(`The data type of 'stdAdd' is: ${stdAddType}`);
boolean
Represents a logical value - true or false.
//boolean
//Represents a logical value - true or false.
console.log(isMaleStd)
// Check the data type of 'isMaleStd'
let isMaleStdType: string = typeof isMaleStd;
console.log(`The data type of 'isMaleStd' is: ${isMaleStdType}`);
console.log(isStdAllow)
// Check the data type of 'isStdAllow'
let isStdAllowType: string = typeof isStdAllow;
console.log(`The data type of 'isStdAllow' is: ${isStdAllowType}`);
null
Represents an intentional absence of an object value.
//null
//Represents an intentional absence of an object value.
console.log(nullValue)
// Check the data type of 'nullValue'
let nullValueType: string = typeof nullValue;
console.log(`The data type of 'nullValue' is: ${nullValueType}`);
undefined
Represents a variable that has been declared but not assigned a value.
//undefined
//Represents a variable that has been declared but not assigned a value.
let StdMarks: undefined = undefined;
console.log(StdMarks)
// Check the data type of 'StdMarks'
let StdMarksType: string = typeof StdMarks;
console.log(`The data type of 'StdMarks' is: ${StdMarksType}`);
any
Represents a dynamic type that can hold any value. Avoid using it whenever
possible, as it reduces the benefits of TypeScript.
//any
//Represents a dynamic type that can hold any value. Avoid using it whenever
possible, as it reduces the benefits of TypeScript.
console.log(StdDOB)
// Check the data type of 'StdDOB'
let StdDOBType: string = typeof StdDOB;
console.log(`The data type of 'StdDOB' is: ${StdDOBType}`);
//Type Inference
//TypeScript has a feature called type inference, which allows the type of a
variable to be automatically determined based on its value.
let age1 = 25; // TypeScript infers 'number' type
let name1 = "John"; // TypeScript infers 'string' type
let isStudent = true; // TypeScript infers 'boolean' type