Core Types
number
string
boolean
object
tuple
Enum
Javascript uses “dynamic types” (resolved at runtime), versus Typescript uses “static types” (set during development). Regular javascript doesn’t include any time assignment.
In TypeScript, you work with types like string
or number
all the times. The core primitive types in TypeScript are all lowercase!
OBject types can also be created for nested objects
Type aliases can be used to “create” your own types.
type User = { name: string; age: number };
const u1: User = { name: 'Max', age: 30 }; // this works!
Using Type Alias to simplify Code
type User = { name: string; age: number };
function greet(user: User) {
console.log('Hi, I am ' + user.name);
}
function isOlder(user: User, checkAge: number) {
return checkAge > user.age;
}
enum Status {ACTIVE, DEACTIVATED, DELETED}
// Using TS Object Inference
const testPerson : {
name: string, // string
age: number, // number
hobbies: string[], // Array
role: [number, string] // Tuple
status: Status // Enum
}= {
name: "John Doe",
age: 30,
hobbies: ['Sports', 'Cooking'],
role: [2, 'author'],
status: Status.ACTIVE
};
// Union Type & Literal Type
function combine(
input1: Combinable,
input2: number | string, // Untion Type
resultType: "as-number" | "as-text" // Literal Type
) {
let result: any;
if (
typeof input1 === "number" &&
typeof input2 === "number" &&
resultType === "as-number"
) {
result = +input1 + +input2;
} else {
result = input1.toString() + input2.toString();
}
return result;
}
type User = {name: string, age: number}
const u1: User = { name: 'John', age: 30}
// Function Return Type by Inference
function add(n1: number, n2: number) {
return n1 + n2;
}
// Defined Return Type
function sec2PrintResult(num: number):void {
console.log("Result: " + num);
}
// Named Function Expression
const sum = function sum(a: number, b: number) {
return a+b
}
// Arrow Function
const sum = (a: number, b: number) : number => a + b