Post

TypeScript Types

TypeScript 로 React Project 작업중 다수의 type error 들로 인한 혼돈으로 typescript types 을 다시한번 정리한다.

Basic Types

TypesExamplesDescription
numberlet num: number = 5;All numbers, no differentiation between integers or floats
stringlet name: string = “Paolo”;All text values
booleanlet result: boolean = false;true or false
object<pre>const person: {
  name: string,
  age: number
} = {
  name: 'Paolo',
  age: '30'
};
</pre>
Any JavaScript object, more specific types (type of object are possible)
Arraylet activities: string[] = [“Climbing”, “Running”]Any JavaScript array, type can be flexible or strict (regarding the element types)
Tuplelet device: [string, number] = [“iPhone”, 699.99]Added by TypeScript: Fixed-length array
Enumenum Role { ADMIN, AUTHOR, CLIENT}Added by TypeScript: Automatically enumerated global constant identifiers
any*Any kind of value, no specific type assignment
Union Typelet phone: number | stringExpecting multiple types
Literal Typelet status: “free” | “busy”Type that is defined with text

Interface

1
2
3
4
5
6
7
interface IAdd {
    num1: number;
    num2: number;
}
function add<IAdd> {
    (...)
}

Type Aliases

1
2
type UnionType = number | string;
type LiteralType = "as-number" | "as-text";

Function Return Types and Void

1
2
3
4
5
6
7
8
function add(n1: number, n2: number): number {
  return n1 + n2;
}

// wide type
function printResult(num: number): void {
  console.log("Result" + num);
}

Function Types

1
2
3
4
5
6
function add(n1: number, n2: number): number {
  return n1 + n2;
}

let combineValues: (a: number, b: number) => number = add;
console.log(conbineValues(9, 9));

Function Types and Callbacks

1
2
3
4
5
6
7
8
function addAndHandle(n1: number, n2: number, callback: (num: number) => void) {
  const result = n1 + n2;
  callback(result);
}

addAndHandle(10, 20, (result) => {
  console.log(result);
});

Unknown Type

1
2
3
4
5
6
let userInput: unknown;
let userNmae: string;
userInput = 5;
if (typeof userInput === "string") {
  userInput = "Max";
}

Never Type

1
2
3
4
5
6
// infinite loop also return never
function generateError(message: string, code: number): never {
  throw { message: message, error: code };
}

generateError("An error occurred!", 500);
This post is licensed under CC BY 4.0 by the author.