Skip to main content

introduction-to-basic-types

1. Introduction to Basic Types

  • Discuss the fundamental data types in TypeScript such as number, string, boolean, null, and undefined.

Certainly! Below are the 20 key points that every student should know about TypeScript's basic types:

1. number Type

TypeScript provides the number type to represent both integers and floating-point values. Unlike some other languages that differentiate between integer and float types, TypeScript uses number for both.

Certainly! Here are concise code examples for each of the TypeScript key points:

  1. number Type
let integerExample: number = 5;
let floatExample: number = 5.5;

2. string Type

The string type is used to represent textual data. TypeScript supports both double-quoted ("hello") and single-quoted ('hello') string literals, as well as template literals (`hello`).

  1. string Type
let doubleQuotedString: string = "hello";
let singleQuotedString: string = 'hello';
let templateLiteralString: string = `hello`;

3. boolean Type

TypeScript uses the boolean type for true/false values. This is fundamental for logical operations and control flow within your application.

  1. boolean Type
let isComplete: boolean = false;
let isValid: boolean = true;

4. null and undefined Types

null and undefined are subtypes that can be assigned to all other types but are not particularly useful on their own. Generally, they're used to signify the absence of value or to reset variables.

  1. null and undefined Types
let emptyValue: null = null;
let uninitializedValue: undefined = undefined;

5. any Type

The any type is a flexible type that allows a variable to be of any type. While it gives maximum flexibility, it should be avoided when possible to make use of TypeScript's type-checking.

  1. any Type
let flexibleVariable: any = 'Start as a string';
flexibleVariable = 42; // Now it's a number
flexibleVariable = false; // Now it's a boolean

6. void Type

The void type is often used as the return type of functions that don't return a value. It's essentially the opposite of the any type.

function logMessage(): void {
console.log("This function doesn't return anything.");
}

7. unknown Type

The unknown type is like a type-safe version of any. You can assign any value to an unknown type, but you can't perform any operations on it without first checking its type.

let unknownValue: unknown = "Hello, TypeScript!";
// To use it, we need to perform a type check
if (typeof unknownValue === "string") {
console.log(unknownValue.toUpperCase()); // This is safe
}

8. Type Annotations

You can explicitly declare the type of a variable using type annotations. For example, let myVar: string = "hello";.

let myVar: string = "hello";

9. Type Inference

TypeScript automatically infers the type of a variable if a type is not explicitly provided. For example, let myVar = "hello"; would automatically infer myVar as a string.

let myVar = "hello"; // myVar is automatically inferred as a string

10. Type Assertion

Type assertion allows you to manually set the type of a variable. It doesn't convert the type but tells the compiler to treat a variable as a specific type, e.g., <string>myVar or myVar as string.

let someValue: any = "This is a string";

// Type assertion syntax
let strLength: number = (<string>someValue).length;

// 'as' syntax
let strLengthAs: number = (someValue as string).length;

11. Union Types

Union types allow variables to be of multiple types. For example, let myVar: string | number = "hello"; makes myVar either a string or a number.

let myVar: string | number = "hello";
myVar = 42; // This is also valid

12. Literal Types

Literal types are used to restrict a variable to exactly one possible value. For example, let myVar: "hello" = "hello"; means myVar can only ever be "hello".

let myVar: "hello" = "hello";
// myVar = "world"; // This would be an error

13. Aliases

Type aliases allow you to create a new name for a type. For instance, you can define type StringOrNumber = string | number; and use it in your code.

type StringOrNumber = string | number;
let value: StringOrNumber = "Okay";
value = 123; // Also valid because of the union type

14. Arrays

TypeScript allows you to specify the type of elements within an array using the [] syntax or the Array<type> generic syntax.

let stringArray: string[] = ["Hello", "World"];
let numberArray: Array<number> = [1, 2, 3, 4, 5];

15. Tuples

Tuples are arrays with a fixed number of elements, where each element can be of a different type. For example, [string, number] would represent a tuple with a string at index 0 and a number at index 1.

let tuple: [string, number] = ["hello", 10];
// tuple = [10, "hello"]; // This would be an error

16. Enums

Enums allow you to define a set of named constants. They can be numeric or string-based.

enum Direction {
Up,
Down,
Left,
Right,
}
let go: Direction = Direction.Up;

For string-based enums:

enum Greeting {
Hello = "HELLO",
Goodbye = "GOODBYE",
}
let welcome: Greeting = Greeting.Hello;

17. Object Types

You can specify the shape of an object using TypeScript's object types, by defining the types for each of the object’s properties.

type User = {
name: string;
age: number;
};
let user: User = { name: "Alice", age: 30 };

18. Intersection Types

Intersection types combine multiple types into one, allowing you to mix various types for complex use-cases, denoted by &.

type Drivable = {
drive(): void;
};
type Sailable = {
sail(): void;
};
type Amphibious = Drivable & Sailable;

19. Control Flow Based Type Narrowing

TypeScript allows you to narrow down types based on control flow statements like if, typeof, and instanceof.

function padLeft(padding: number | string, input: string): string {
if (typeof padding === "number") {
return new Array(padding + 1).join(" ") + input; // padding is treated as a number
}
return padding + input; // padding is treated as a string
}

20. Readonly and Const Assertions

You can make object properties readonly using the readonly modifier, and assert a variable as constant using as const, to indicate that its value should never change.

type ReadonlyUser = {
readonly id: number;
readonly name: string;
};
let user: ReadonlyUser = { id: 1, name: "Alice" };
// user.id = 2; // Error, id is readonly

let literalConst = "hello" as const;
// literalConst = "world"; // Error, literalConst is a constant