state in typescript

To state something in TypeScript, you can use different features and syntax depending on what you're trying to achieve. Here are a few examples:

  1. Declare a variable with a specific type:
index.ts
let myVariable: string = "hello world";
40 chars
2 lines
  1. Define a function with typed parameters and return values:
index.ts
function addNumbers(a: number, b: number): number {
  return a + b;
}
70 chars
4 lines
  1. Create a TypeScript interface to define a custom type:
index.ts
interface Person {
  name: string;
  age: number;
  email?: string;
}

let john: Person = { name: "John", age: 25 };
117 chars
8 lines
  1. Use TypeScript's generics to make functions and classes more flexible:
index.ts
function toArray<T>(arg: T): T[] {
  return [arg];
}

let arr = toArray("hello"); // arr is of type string[]
109 chars
6 lines
  1. Extend existing types to add new functionality or constraints:
index.ts
interface Array<T> {
  filterUndef(): T[];
}

Array.prototype.filterUndef = function() {
  return this.filter(item => item !== undefined) as T[];
};

let myArray: (string | undefined)[] = ["hello", undefined, "world"];
let filteredArray = myArray.filterUndef(); // filteredArray is of type string[]
299 chars
11 lines

gistlibby LogSnag