1// simple type
2type Websites = 'www.google.com' | 'reddit.com';
3let mySite: Websites = 'www.google.com' //pass
4//or
5let mySite: Website = 'www.yahoo.com' //error
6// the above line will show error because Website type will only accept 2 strings either 'www.google.com' or 'reddit.com'.
7// another example.
8type Details = { id: number, name: string, age: number };
9let student: Details = { id: 803, name: 'Max', age: 13 }; // pass
10//or
11let student: Details = { id: 803, name: 'Max', age: 13, address: 'Delhi' } // error
12// the above line will show error because 'address' property is not assignable for Details type variables.
13//or
14let student: Details = { id: 803, name: 'Max', age: '13' }; // error
15// the above line will show error because string value can't be assign to the age value, only numbers.
16
17
18
1// define your parameter's type inside the parenthesis
2// define your return type after the parenthesis
3
4function sayHello(name: string): string {
5 console.log(`Hello, ${name}`!);
6}
7
8sayHello('Bob'); // Hello, Bob!
1// cannot use object for type defination because this is not recommended
2// use Record<string, any> this same with object
3
4const name: string = "john doe"
5const age: number = 30
6
7const days1: string[] = ["sunday","monday","thuesday","wenesday"]
8const numb1: number[] = [1,2,3,4,5]
9
10const days2: Array<string> = ["sunday","monday","thuesday","wenesday"]
11const numb2: Array<number> = [1,2,3,4,5]
12
13const person: Record<string, any> = {
14 name: "john doe",
15 age: 30
16}
17
18async function name(): Promise<string> {
19 return "john doe"
20}
21
22name().then(console.log)
23
24async function str(): Promise<string[]> {
25 return ["sunday","monday","thuesday","wenesday"]
26}
27
28str().then(console.log)
29
30async function int(): Promise<int[]> {
31 return [1,2,3,4,5]
32}
33
34int().then(console.log)
35
36async function objectValue(): Promise<Record<string, any>> {
37 const person: Record<string, any> = {
38 name: "john doe",
39 age: 30
40 }
41 return person
42}
43
44objectValue().then(console.log)
45
46async function objectValueMulti(): Promise<Record<string, any>[]> {
47 const person: Record<string, any>[] = [{
48 name: "john doe",
49 age: 30
50 },{
51 name: "jane doe",
52 age: 30
53 }]
54 return person
55}
56
57objectValueMulti().then(console.log)
1interface Date {
2 toString(): string;
3 setTime(time: number): number;
4 // ...
5}
6
1var name: string = "Anna";
2let notes: (number | string)[] = ["Get Food", 23, "Call the previous number when betting"];
3
1type Props = {
2 item: CartItemType;
3 addToCart: (clickedItem: CartItemType) => void;
4 removeFromCart: (id: number) => void;
5};