Skip to content

Instantly share code, notes, and snippets.

@RanjanSushant
Created January 4, 2022 07:43
Show Gist options
  • Save RanjanSushant/ef5646067a095cbce799f11df92cc0f1 to your computer and use it in GitHub Desktop.
Save RanjanSushant/ef5646067a095cbce799f11df92cc0f1 to your computer and use it in GitHub Desktop.
Primitives in TypeScript
let message: string = "Hello World"; // string type variable
let myNum: number = 42; // number type variable
let isReal: boolean = true; // boolean type variable
let special: any = "Any type"; // any type variable
special = 13; // any type doesn't cause any type checking errors
// Arrays
let numList: number[] = [1, 3, 5, 7] // a number array
let strList: string[] = ["Luke", "I", "am", "your", "father"] // a string array
// Functions
//This function takes two string types as input and returns a string output
function greeting(firstName: string, lastName: string): string {
return firstName + lastName
}
let fullName = greeting("Han", "Solo")
console.log(fullName)
// Anonymous functions
// Inferred type
const names = ["Stark", "Potts", "Parker"];
// Contextual typing for arrow functions
names.forEach((s) => {
console.log(s.toUpperCase());
});
// Tuples - Special Arrays with fixed type elements
const universe: [number, string] = [1, "Marvel"];
// Enum type
enum Seasons { SUMMER, WINTER, SPRING, AUTUMN };
// can be accessed as
console.log(Seasons.WINTER)
// Unions
let data:(number | string) = 99;
data = "ninety nine" //valid because it is a union
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment