Skip to main content

Command Palette

Search for a command to run...

2) Typescript Variables

Updated
  1. Static Typing in TypeScript
    Static typing means variables, functions, and objects have predefined types checked during compile time.

    // Javascript Example
    let age = 25;
    age = "Rahul"; // Allowed in JS
    
    // Typescript Example
    let age: number = 25;
    
    // Error
    age = "Rahul";
    

    Benefits
    Prevents runtime errors
    Better IntelliSense
    Easier refactoring
    Self-documenting code
    Safer React props/state

  2. Primitive Type Variables
    In TypeScript, the base types (or primitive types) are similar to those in JavaScript. They include,
    i) boolean: Represents a true/false value.

    let isDone: boolean = false;
    

    ii) number: Represents all numeric values, including integers and floating-point numbers.

    let decimal: number = 6;
    let hex: number = 0xf00d;
    let binary: number = 0b1010;
    let octal: number = 0o744;
    

    iii) string: Represents text data.

    let color: string = "blue";
    color = 'red';
    

    iv) null and undefined: Represents the null and undefined values. By default, null and undefined are sub-types of all other types.

    let u: undefined = undefined;
    let n: null = null;
    

    v) any: Represents a dynamic type that can hold any value, useful when you don't know the type in advance or are migrating JavaScript code.

    let notSure: any = "maybe a string instead";
    notSure = false; // okay, definitely a boolean
    notSure = 45; // okey, definitely a number
    

    vi) unknown: Similar to any, but safer because you need to do some type checking before performing operations on it.

    let notSure: unknown = 4;
    notSure = "maybe a string instead";
    if (typeof notSure === "string") {
        console.log(notSure.toUpperCase()); // OK
    }
    

    vii) void: Represents the absence of any type. It's commonly used as the return type for functions that do not return a value.

    function warnUser(): void {
        console.log("This is my warning message");
    }
    

    xi) never: Represents the type of values that never occur. This is used for functions that always throw an exception or never return.

    function error(message: string): never {
        throw new Error(message);
    }
    
    function fail() {
        return error("Something failed");
    }
    
    function infiniteLoop(): never {
        while (true) {}
    }
    
  3. Arrays in TypeScript
    Represents a collection of values of a specific type.

    let list: number[] = [1, 2, 3];
    let technologies: string[] = ["React", "TypeScript", "Node"];
    
    // Generic Array Syntax
    let users: Array<string> = ["Rahul", "Amit"];
    

    React Example — Array Rendering

    type SkillsProps = {
      skills: string[];
    };
    
    function SkillComponent({ skills }: SkillsProps) {
      return (
        <ul>
          {skills.map((skill, index) => (
            <li key={index}>{skill}</li>
          ))}
        </ul>
      );
    }
    
    <SkillComponent skills={["React", "TypeScript", "Redux"]} />
    
  4. Tuples in Typescript
    Represents an array with a fixed number of elements where each element can have a different type.

    let employee: [number, string] = [101, "Rahul"];
    

    React example with Typescript

    type UserTuple = [number, string];
    
    const user: UserTuple = [1, "Rahul"];
    
    function Profile() {
      return (
        <div>
          <p>ID: {user[0]}</p>
          <p>Name: {user[1]}</p>
        </div>
      );
    } 
    
  5. Enums in Typescript
    Represents a way to define a set of named constants.

    enum Color {
      Red, 
      Green, 
      Blue
    };
    let c: Color = Color.Green;
    console.log(c); // 1
    

    React Example with Enum

    enum Theme {
      Light = "LIGHT",
      Dark = "DARK"
    }
    
    type HeaderProps = {
      theme: Theme;
    };
    
    function HeaderComponent({ theme }: HeaderProps) {
      return (
        <div>
          Current Theme: {theme}
        </div>
      );
    }
    
    <HeaderComponent theme={Theme.Dark} />
    
  6. Literal Types in TypeScript
    Literal types restrict values to exact predefined values.
    i) String Literal Type

    type Direction = "left" | "right" | "top" | "bottom";
    
    let move: Direction = "left";
    
    // Error
    move = "center";
    

    ii) Numeric Literal Type

    type Dice = 1 | 2 | 3 | 4 | 5 | 6;
    
    let diceValue: Dice = 4;
    

    React Example with Literal Types

    type ButtonVariant = "primary" | "secondary" | "danger";
    
    type ButtonProps = {
      label: string;
      variant: ButtonVariant;
    };
    
    function Button({ label, variant }: ButtonProps) {
      return (
        <button className={variant}>
          {label}
        </button>
      );
    }
    
    <Button label="Save" variant="primary" />
    <Button label="Delete" variant="danger" />