Last active
October 1, 2022 10:14
-
-
Save QuocCao-dev/2b65864f04a570376bb2a7cf6a369626 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// String Variable With Explicit Annotation | |
let movieTitle: string = "Amadeus"; | |
movieTitle = "Arrival"; | |
movieTitle = 9; //This results in an error! | |
movieTitle.toUpperCase(); | |
// Number Variable with explicit annotation | |
let numCatLives: number = 9; | |
numCatLives += 1; | |
numCatLives = "zero"; //Error! | |
// Explicitly typed boolean variable: | |
let gameOver: boolean = false; | |
gameOver = true; | |
gameOver = "true"; //error!! | |
// Type Inference | |
let tvShow = "Olive Kitteridge"; | |
tvShow = "The Other Two"; | |
tvShow = false; | |
let isFunny = false; | |
isFunny = true; | |
isFunny = "asd"; | |
// the any type | |
let thing: any = "hello"; //This is not a great idea! | |
thing = 1; | |
thing = false; | |
thing(); | |
thing.toUpperCase(); | |
const movies = ["Arrival", "The Thing", "Aliens", "Amadeus"]; | |
let foundMovie: string; | |
for (let movie of movies) { | |
if (movie === "Amadeus") { | |
foundMovie = "Amadeus"; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function parameter type annotations: | |
const doSomething = (person: string, age: number, isFunny: boolean) => {}; | |
// Return type annotation: | |
function greet(person: string = "stranger"): string { | |
return `Hi there, ${person}!`; | |
} | |
function square(num: number): number { | |
return num * num; | |
} | |
square(3); | |
greet("Tonya Harding"); | |
doSomething("ChickenFace", 78, true); | |
// Arrow function: | |
const add = (x: number, y: number): number => { | |
return x + y; | |
}; | |
// Contextual Type Clues | |
const colors = ["red", "orange", "yellow"]; | |
colors.map((color) => { | |
return color.toUpperCase(); | |
}); | |
// Void | |
function printTwice(msg: string): void { | |
console.log(msg); | |
console.log(msg); | |
} | |
// Never | |
function makeError(msg: string): never { | |
throw new Error(msg); | |
} | |
function gameLoop(): never { | |
while (true) { | |
console.log("GAME LOOP RUNNING!"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ********************************************** | |
// ******************* PART 1 ******************* | |
// ********************************************** | |
// Write a function called "twoFer" that accepts a person's name | |
// It should return a string in the format "one for <name>, one for me" | |
// If no name is provided, it should default to "you" | |
// twoFer() => "One for you, one for me" | |
// twoFer("Elton") => "One for Elton, one for me" | |
function twoFer(person: string = "you"): string { | |
return `One for ${person}, one for me.`; | |
} | |
console.log(twoFer()); | |
console.log(twoFer("Elvis")); | |
// ********************************************** | |
// ******************* PART 2 ******************* | |
// ********************************************** | |
// Write a isLeapyear() function that accepts a year and returns true/false depending on if the year is a leap year | |
// isLeapYear(2012) => true | |
// isLeapYear(2013) => false | |
// To determine whether a year is a leapyear, use this "formula": | |
// A YEAR IS A LEAPYEAR IF | |
// - year is a multiple of 4 AND not a multiple of 100 | |
// OR... | |
// - year is a multiple of 400 | |
// hint - use modulo | |
// const isLeapYear = (year: number): boolean => { | |
// if (year % 4 === 0 && year % 100 !== 0) { | |
// return true; | |
// } else if(year % 400 === 0){ | |
// return true | |
// } | |
// return false; | |
// }; | |
const isLeapYear = (year: number): boolean => { | |
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; | |
}; | |
console.log(isLeapYear(2012)); | |
console.log(isLeapYear(2013)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ********************************************** | |
// ******************* PART 1 ******************* | |
// ********************************************** | |
// Write a function called "twoFer" that accepts a person's name | |
// It should return a string in the format "one for <name>, one for me" | |
// If no name is provided, it should default to "you" | |
// twoFer() => "One for you, one for me" | |
// twoFer("Elton") => "One for Elton, one for me" | |
// ********************************************** | |
// ******************* PART 2 ******************* | |
// ********************************************** | |
// Write a isLeapyear() function that accepts a year and returns true/false depending on if the year is a leap year | |
// isLeapYear(2012) => true | |
// isLeapYear(2013) => false | |
// To determine whether a year is a leapyear, use this "formula": | |
// A YEAR IS A LEAPYEAR IF | |
// - year is a multiple of 4 AND not a multiple of 100 | |
// OR... | |
// - year is a multiple of 400 | |
// hint - use modulo |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Objects as parameters: | |
function printName(person: { first: string; last: string }): void { | |
console.log(`${person.first} ${person.last}`); | |
} | |
printName({ first: "Thomas", last: "Jenkins" }); | |
const singer = { first: "Mick", last: "Jagger", age: 473, isAlive: true }; | |
printName(singer); | |
// let coordinate: { x: number; y: number } = { x: 34, y: 2 }; | |
// function randomCoordinate(): { x: number; y: number } { | |
// return { x: Math.random(), y: Math.random() }; | |
// } | |
// function doublePoint(point: { x: number; y: number }): { | |
// x: number; | |
// y: number; | |
// } { | |
// return { x: point.x * 2, y: point.y * 2 }; | |
// } | |
// type Point = { | |
// x: number; | |
// y: number; | |
// }; | |
let coordinate: Point = { x: 34, y: 2 }; | |
function randomCoordinate(): Point { | |
return { x: Math.random(), y: Math.random() }; | |
} | |
function doublePoint(point: Point): Point { | |
return { x: point.x * 2, y: point.y * 2 }; | |
} | |
type Song = { | |
title: string; | |
artist: string; | |
numStreams: number; | |
credits: { producer: string; writer: string }; | |
}; | |
function calculatePayout(song: Song): number { | |
return song.numStreams * 0.0033; | |
} | |
function printSong(song: Song): void { | |
console.log(`${song.title} - ${song.artist}`); | |
} | |
const mySong: Song = { | |
title: "Unchained Melody", | |
artist: "Righteous Brothers", | |
numStreams: 12873321, | |
credits: { | |
producer: "Phil Spector", | |
writer: "Alex North", | |
}, | |
}; | |
const earnings = calculatePayout(mySong); | |
console.log(earnings); | |
printSong(mySong); | |
type Point = { | |
x: number; | |
y: number; | |
z?: number; | |
}; | |
const myPoint: Point = { x: 1, y: 3 }; | |
type User = { | |
readonly id: number; | |
username: string; | |
}; | |
const user: User = { | |
id: 12837, | |
username: "catgurl", | |
}; | |
console.log(user.id); | |
user.id; | |
type Circle = { | |
radius: number; | |
}; | |
type Colorful = { | |
color: string; | |
}; | |
type ColorfulCircle = Circle & Colorful; | |
const happyFace: ColorfulCircle = { | |
radius: 4, | |
color: "yellow", | |
}; | |
type Cat = { | |
numLives: number; | |
}; | |
type Dog = { | |
breed: string; | |
}; | |
type CatDog = Cat & | |
Dog & { | |
age: number; | |
}; | |
const christy: CatDog = { | |
numLives: 7, | |
breed: "Husky", | |
age: 9, | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Write the Movie type alias to make the following two variables properly typed | |
// Make sure that "originalTitle" is optional and "title" is readonly | |
const dune: Movie = { | |
title: "Dune", | |
originalTitle: "Dune Part One", | |
director: "Denis Villeneuve", | |
releaseYear: 2021, | |
boxOffice: { | |
budget: 165000000, | |
grossUS: 108327830, | |
grossWorldwide: 400671789, | |
}, | |
}; | |
const cats: Movie = { | |
title: "Cats", | |
director: "Tom Hooper", | |
releaseYear: 2019, | |
boxOffice: { | |
budget: 95000000, | |
grossUS: 27166770, | |
grossWorldwide: 73833348, | |
}, | |
}; | |
// Write a function called getProfit that accepts a single Movie object | |
// It should return the movie's worldwide gross minus its budget | |
// For example... | |
// getProfit(cats) => -21166652 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// String array | |
const activeUsers: string[] = []; | |
activeUsers.push("Tony"); | |
// Array of numbers | |
const ageList: number[] = [45, 56, 13]; | |
ageList[0] = 99; | |
// Alternate Syntax: | |
// const bools: Array<boolean> = [] | |
const bools: boolean[] = []; | |
type Point = { | |
x: number; | |
y: number; | |
}; | |
const coords: Point[] = []; | |
coords.push({ x: 23, y: 8 }); | |
// Multi-dimensional string array | |
const board: string[][] = [ | |
["X", "O", "X"], | |
["X", "O", "X"], | |
["X", "O", "X"], | |
]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1 type Point = {x: number, y: number}; | |
// 2 let coors: Point[] = [] | |
// 3 write a function in order to generate default Point => {x: 0, y: 0} generateOriginalPoint() | |
// 4 write a function in order to generate a random Point => {x: random, y: random} generateRandomPoint() | |
// 5 loops push 100 default Point and 100 randomPoint |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Basic Union Type: | |
let age: number | string = 21; | |
age = 23; | |
age = "24"; | |
type Point = { | |
x: number; | |
y: number; | |
}; | |
type Loc = { | |
lat: number; | |
long: number; | |
}; | |
// Union type with type aliases | |
let coordinates: Point | Loc = { x: 1, y: 34 }; | |
coordinates = { lat: 321.213, long: 23.334 }; | |
// Function parameter union type: | |
function printAge(age: number | string): void { | |
console.log(`You are ${age} years old`); | |
} | |
function calculateTax(price: number | string, tax: number) { | |
if (typeof price === "string") { | |
price = parseFloat(price.replace("$", "")); | |
} | |
return price * tax; | |
} | |
// const nums: number[] = [1,2,3,4] | |
// const stuff: any[] = [1,2,3,4, true, "asdas", {}] | |
// const stuff: (number | string)[] = [1,2,3, "das"] | |
// const stuff: number[] | string[] = ["asd", "asd", 1] | |
// Union Type With Arrays | |
const coords: (Point | Loc)[] = []; | |
coords.push({ lat: 321.213, long: 23.334 }); | |
coords.push({ x: 213, y: 43 }); | |
// Literal Types | |
let zero: 0 = 0; | |
let mood: "Happy" | "Sad" = "Happy"; | |
mood = "Sad"; | |
type DayOfWeek = | |
| "Monday" | |
| "Tuesday" | |
| "Wednesday" | |
| "Thursday" | |
| "Friday" | |
| "Saturday" | |
| "Sunday"; | |
let today: DayOfWeek = "Sunday"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const color: [number, number, number] = [255, 0, 45]; | |
const myColor: [number, number, string] = [255, 0, "asd"]; | |
type HTTPResponse = [number, string]; | |
const goodRes: HTTPResponse = [200, "OK"]; | |
// An array of tuples: | |
const responses: HTTPResponse[] = [ | |
[404, "Not Found"], | |
[200, "OK"], | |
]; | |
// Enum Example: | |
enum OrderStatus { | |
PENDING, | |
SHIPPED, | |
DELIVERED, | |
RETURNED, | |
} | |
const myStatus = OrderStatus.DELIVERED; | |
function isDelivered(status: OrderStatus) { | |
return status === OrderStatus.DELIVERED; | |
} | |
isDelivered(OrderStatus.RETURNED); | |
// String Enum: | |
enum ArrowKeys { | |
UP = "up", | |
DOWN = "down", | |
LEFT = "left", | |
RIGHT = "right", | |
} | |
enum HTTP_STATUS { | |
OK = 200, | |
NOT_FOUND = 404, | |
INTERNAL_SERVER = 500, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment