|
| 1 | +// Define a TypeScript interface |
| 2 | +interface Person { |
| 3 | + name: string |
| 4 | + age: number |
| 5 | +} |
| 6 | + |
| 7 | +// Create an array of objects with the defined interface |
| 8 | +const people: Person[] = [ |
| 9 | + { name: 'Alice', age: 30 }, |
| 10 | + { name: 'Bob', age: 25 }, |
| 11 | + { name: 'Charlie', age: 35 }, |
| 12 | +] |
| 13 | + |
| 14 | +// eslint-disable-next-line no-console |
| 15 | +const log = console.log |
| 16 | + |
| 17 | +// Use a for...of loop to iterate over the array |
| 18 | +for (const person of people) { |
| 19 | + log(`Hello, my name is ${person.name} and I am ${person.age} years old.`) |
| 20 | +} |
| 21 | + |
| 22 | +// Define a generic function |
| 23 | +function identity< T >(arg: T): T { |
| 24 | + return arg |
| 25 | +} |
| 26 | + |
| 27 | +// Use the generic function with type inference |
| 28 | +const result = identity( |
| 29 | + 'TypeScript is awesome', |
| 30 | +) |
| 31 | +log(result) |
| 32 | + |
| 33 | +// Use optional properties in an interface |
| 34 | +interface Car { |
| 35 | + make: string |
| 36 | + model?: string |
| 37 | +} |
| 38 | + |
| 39 | +// Create objects using the interface |
| 40 | +const car1: Car = { make: 'Toyota' } |
| 41 | +const car2: Car = { |
| 42 | + make: 'Ford', |
| 43 | + model: 'Focus', |
| 44 | +} |
| 45 | + |
| 46 | +// Use union types |
| 47 | +type Fruit = 'apple' | 'banana' | 'orange' |
| 48 | +const favoriteFruit: Fruit = 'apple' |
| 49 | + |
| 50 | +// Use a type assertion to tell TypeScript about the type |
| 51 | +const inputValue: any = '42' |
| 52 | +const numericValue = inputValue as number |
| 53 | + |
| 54 | +// Define a class with access modifiers |
| 55 | +class Animal { |
| 56 | + private name: string |
| 57 | + constructor(name: string) { |
| 58 | + this.name = name |
| 59 | + } |
| 60 | + |
| 61 | + protected makeSound(sound: string) { |
| 62 | + log(`${this.name} says ${sound}`) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// Extend a class |
| 67 | +class Dog extends Animal { |
| 68 | + constructor(private alias: string) { |
| 69 | + super(alias) |
| 70 | + } |
| 71 | + |
| 72 | + bark() { |
| 73 | + this.makeSound('Woof!') |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +const dog = new Dog('Buddy') |
| 78 | +dog.bark() |
| 79 | + |
| 80 | +function fn(): string { |
| 81 | + return `hello${1}` |
| 82 | +} |
| 83 | + |
| 84 | +log(car1, car2, favoriteFruit, numericValue, fn()) |
0 commit comments