Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
typescript notes
All from here: https://microsoft.github.io/TypeScript-New-Handbook/chapters
run with --strict to catch more stuff
number[] = array of numbers,
also Array<number>
string[] = array of string
any = typescript wont yell at you for anything
let obj: any = { x: 0 };
// wont produce error
obj.foo();
// TypeScript doesn't use "types on the left"-style declarations like int x = 0; Type annotations will always go after the thing being typed.
// Functions
// Parameter type annotation
function greet(name: string) {
console.log("Hello, " + name.toUpperCase() + "!!");
}
// RETURN type annotations
// you usually don't need a return type annotation because TypeScript will infer the function's return type based on its return statements.
function getFavoriteNumber(): number {
return 26;
}
// Objects
function printCoord(pt: { x: number, y: number }) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
// ^ If you don't specify a type, it will be assumed to be any.
// Object types can also specify that some or all of their properties are optional. To do this, add a ? after the property
function printName(obj: { first: string, last?: string}) {
// ...
}
// Both OK
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });
// When you read from an optional property, you'll have to check for undefined before using it.
// basically like regular JS
// Union Types = multiple types
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
// Error
printId([1, 2]);
Typescript will yell at you if you try and do something that not all types will accept
bad:
function printId(id: number | string) {
console.log(id.toUpperCase());
}
But you can use if logic to make it good (refered to as 'narrowing'):
function printId(id: number | string) {
if (typeof id === "string") {
// In this branch, id is of type 'string'
console.log(id.toUpperCase());
} else {
// Here, id is of type 'number'
console.log(id);
}
}
// Type Aliases
So far we have been declaring types inline but, what if - yes - you guessed it - did not have to write them inline
type Point = {
x: number,
y: number
};
// Exactly the same as the earlier example
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
type ID = number | string;
// Can even do werid stuff:
type Age = number;
type Weight = number;
const myAge: Age = 73;
// *not* an error
const myWeight: Weight = myAge;
// You can also have LITERAL types which is literally saying 'it should be this exact string'
function printText(s: string, alignment: "left" | "right" | "center") {
// ...
}
printText("Hello, world", "left");
printText("G'day, mate", "centre");
// same w return value things
function compare(a: string, b: string): -1 | 0 | 1 {
return a === b ? 0 : a > b ? 1 : -1;
}
// The type boolean itself is actually just an alias for the union true | false.
// Writing ! after any expression is effectively a type assertion that the value isn't null or undefined:
function liveDangerously(x?: number | null) {
// No error
console.log(x!.toFixed());
}
// leftoff https://microsoft.github.io/TypeScript-New-Handbook/chapters/narrowing/#instanceof-narrowing
// Can also use 'instanceof' to narrow like you would typeof
function logValue(x: Date | string) {
if (x instanceof Date) {
console.log(x.toUTCString());
}
else {
console.log(x.toUpperCase());
}
}
// You can use the | thingy to define something as one of two types
// as to avoid using the ? thingy to say things are options.
// This helps not have to do so many type checks or stuff that can confuse the compiler.
// For EG
interface Shape {
kind: "circle" | "square";
radius?: number;
sideLength?: number;
}
// can be turned into
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;
function getArea(shape: Shape) {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
}
// Look here to see why exactly if you forgot: https://microsoft.github.io/TypeScript-New-Handbook/chapters/narrowing/#discriminated-unions
// Am here: https://microsoft.github.io/TypeScript-New-Handbook/chapters/more-on-functions/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment