Skip to content

Instantly share code, notes, and snippets.

@s1rat-dev
Created February 20, 2022 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s1rat-dev/23a037e9024830942296ab8fdfac0499 to your computer and use it in GitHub Desktop.
Save s1rat-dev/23a037e9024830942296ab8fdfac0499 to your computer and use it in GitHub Desktop.
[TYPESCRIPT] Annotations for arrays.
const carMakers = ['ford','toyota','honda'];
const dates = [new Date(), new Date()];
const carsByMake: string[][] = [];
// Help with inference when extracting values
const car = carMakers[0];
const myCare = carMakers.pop();
// Prevent incompatible values
// carMakers.push(100); -> Type error.
// Help with 'map'
carMakers.map((car: string): string => {
// Show methods that belong to string.
return car.toUpperCase();
})
// Multiple types - Flexible types
// const importantDates: (string | Date)[]
const importantDates = [new Date(), '2030-10-10'];
const otherImportantDates: (Date | string)[] = []
importantDates.push('2020-10-10');
otherImportantDates.push('2020-10-10');
importantDates.push(new Date());
otherImportantDates.push(new Date());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment