Typescript Primitive Types String Number Boolean Complete Guide
Understanding the Core Concepts of TypeScript Primitive Types string, number, boolean
TypeScript Primitive Types: string, number, boolean
Introduction
1. String
The string
type represents textual data and is used to manipulate text within applications. Strings can be defined using either single quotes (' '
), double quotes (" "
), or template literals (backticks) in TypeScript.
Important Information:
Usage: Ideal for defining variable containing text or character sequences.
Methods: String types come with numerous built-in methods for manipulating and interacting with string data, such as
split()
,concat()
,toLocaleUpperCase()
,length()
, etc.Example:
let myName: string = "Alice"; let greeting: string = `Hello, ${myName}!`; // Template literal
Type Inference: TypeScript can automatically infer the type if the variable is initialized with a string value.
let city = "New York"; // TypeScript infers type as string
2. Number
The number
type covers all integer and floating-point values in TypeScript. Unlike some other languages, TypeScript does not differentiate between different numeric types like integers and floats. All numbers in TypeScript are double-precision floating-point format as defined by the ECMAScript standard (IEEE 754).
Important Information:
Usage: Ideal for defining variables containing numerical data.
Operations: It supports all arithmetic operations such as addition (
+
), subtraction (-
), multiplication (*
), division (/
), modulus (%
), exponentiation (**
), increment (++
), and decrement (--
).Example:
let age: number = 25; let pi: number = 3.14159; let result: number = age + pi;
Type Inference: TypeScript can infer the type if a numeric value is assigned.
let temperature = 36.6; // TypeScript infers type as number
3. Boolean
The boolean
type represents logical values in TypeScript, and it can only hold two values: true
or false
. This type is essential for control flow operations such as conditional statements and loops.
Important Information:
Usage: Ideal for defining variables that represent true/false conditions.
Logical Operations: Booleans are crucial in logical operations such as conjunction (
&&
), disjunction (||
), and negation (!
).Example:
let isLoggedIn: boolean = true; let isCompleted: boolean = false;
Type Inference: TypeScript can infer the type if a boolean value is assigned.
Online Code run
Step-by-Step Guide: How to Implement TypeScript Primitive Types string, number, boolean
Step-by-Step Examples for TypeScript Primitive Types
1. String Type
The string
type in TypeScript is used for representing text values. Let's look at some examples.
Example 1: Declare and Initialize a String
// Declare a variable of type string
let userName: string;
// Initialize the variable
userName = "Alice";
console.log(userName); // Output: Alice
Example 2: Concatenation of Strings
let firstName: string = "John";
let lastName: string = "Doe";
// Concatenate strings
let fullName: string = firstName + " " + lastName;
console.log(fullName); // Output: John Doe
Example 3: Template Literals
Template literals are a convenient way to embed expressions within string literals. They use backticks (`
) and ${expression}
for embedding expressions.
let age: number = 25;
let greeting: string = `Hello, my name is ${firstName} ${lastName} and I am ${age} years old.`;
console.log(greeting); // Output: Hello, my name is John Doe and I am 25 years old.
2. Number Type
The number
type in TypeScript is used for both integers and floating-point values.
Example 1: Declare and Initialize a Number
// Declare and initialize a variable of type number
let age: number = 28;
console.log(age); // Output: 28
Example 2: Basic Arithmetic Operations
let num1: number = 10;
let num2: number = 20;
let sum: number = num1 + num2;
let difference: number = num2 - num1;
let product: number = num1 * num2;
let quotient: number = num2 / num1;
console.log(sum); // Output: 30
console.log(difference); // Output: 10
console.log(product); // Output: 200
console.log(quotient); // Output: 2
Example 3: Type Inference with Numbers
TypeScript can automatically infer the type of a variable if you initialize it.
let count = 100; // TypeScript infers that count is of type number
console.log(count); // Output: 100
3. Boolean Type
The boolean
type in TypeScript is used to represent truth values: true
or false
.
Example 1: Declare and Initialize a Boolean
// Declare and initialize a variable of type boolean
let isLoggedIn: boolean;
// Set the value
isLoggedIn = true;
console.log(isLoggedIn); // Output: true
Example 2: Boolean Expression
You can use boolean values in conditions to control the flow of your program.
let isAuthenticated: boolean = false;
if (isAuthenticated) {
console.log("User is logged in.");
} else {
console.log("User is not logged in.");
}
// Output: User is not logged in.
Example 3: Logical Operators
Boolean values can be used with logical operators such as &&
(and), ||
(or), and !
(not).
Top 10 Interview Questions & Answers on TypeScript Primitive Types string, number, boolean
1. What are the primitive types in TypeScript?
Answer: TypeScript has three main primitive types: string
, number
, and boolean
. These types represent values at the most basic level in the language.
2. How do you define a variable with a string type in TypeScript?
Answer: You can define a variable with a string type using the string
keyword. For example:
let greeting: string = "Hello, TypeScript!";
3. Can TypeScript primitive types be inferred automatically?
Answer: Yes, TypeScript uses type inference to automatically determine the type of a variable based on its initial value. For example:
let inferredStringValue = "Hello"; // TypeScript infers this as a string
let inferredNumberValue = 123; // TypeScript infers this as a number
let inferredBooleanValue = true; // TypeScript infers this as a boolean
4. How do you handle numeric operations in TypeScript?
Answer: Numeric operations in TypeScript are similar to JavaScript and support all standard arithmetic operators (+
, -
, *
, /
). You can define numbers using the number
type keyword. Example:
let num1: number = 10;
let num2: number = 5;
let sum: number = num1 + num2; // sum will be 15
5. What is the difference between single and double quotes in TypeScript strings?
Answer: In TypeScript, both single ('
) and double ("
) quotes are used to define string literals, and there is no functional difference between them. String templates, which use backticks (`
), allow embedding expressions and multi-line strings, like so:
let name: string = 'John';
let message1: string = "Hello, " + name + "!";
let message2: string = `Hello, ${name}!
How are you today?`;
Both message1
and message2
hold valid string data.
6. Can you concatenate a string and a number directly in TypeScript?
Answer: While TypeScript will allow you to concatenate a string and a number directly for purposes of code backwards compatibility with JavaScript, it is often better practice to explicitly convert types to avoid unexpected results. Example:
let concatenatedMessage: string = "The magic number is " + 42;
console.log(concatenatedMessage); // Output: "The magic number is 42"
// Explicit conversion
let concatenatedMessageExplicit: string = "The magic number is " + String(42);
console.log(concatenatedMessageExplicit); // Output: "The magic number is 42"
7. How do you declare a boolean type variable in TypeScript?
Answer: Boolean type variables are declared using the boolean
keyword. Only two values are allowed: true
or false
.
let isActive: boolean = true;
let isLoggedIn: boolean = false;
8. Are there any restrictions on the values of these primitive types?
Answer: Yes, there are some restrictions:
- String: Must be enclosed in single (
'
), double ("
), or backtick (`
) quotes. - Number: Supports floating-point arithmetic, and binary, octal, decimal, hexadecimal representations.
- Boolean: Only accepts boolean values:
true
orfalse
.
9. How does TypeScript handle type coercion during operations?
Answer: TypeScript does not perform implicit type coercion during operations but JavaScript runtime does when compiled to JS. TypeScript enforces type safety, preventing operations that involve implicitly different types unless explicitly told to do so (for example via type assertions).
let x: string = '5';
let y: number = 10;
let resultImplicit: string = x + y; // TypeScript compiles this even if not ideal
// Corrected with explicit conversion
let resultCorrect: string = Number(x) + y; // Ensures type safety and correct behavior
10. Can you provide examples of each primitive type’s usage in a conditional statement?
Answer: Absolutely! Here’s how each type can be used in a conditional statement:
- String: Often used to compare text values in conditions.
Login to post a comment.