Skip to content

Instantly share code, notes, and snippets.

@arnoldc
Last active August 14, 2023 23:54
Show Gist options
  • Select an option

  • Save arnoldc/20766ef6938b6b5257ea252cb909db87 to your computer and use it in GitHub Desktop.

Select an option

Save arnoldc/20766ef6938b6b5257ea252cb909db87 to your computer and use it in GitHub Desktop.
[Typescript] General Tips
/*
* ──────────── Table of contents ────────────
*
* @1 - object as type
* @2 - enums
* @3 - is
* @4 - satisfies
* @5 - optional props
* @6 - types vs interface
* ──────────── Table of contents ────────────
*/
// @1 - object as type
const AuthMethod = {
push: "Push",
sms: "SMS",
voice: "Voice",
} as const;
type AuthMethod = typeof AuthMethod[keyof typeof AuthMethod];
// @2 - enums
//Bad ❌
enum BadState {
InProgress,
Success,
Fail,
}
BadState.InProgress; // (enum member) State.InProgress = 0
BadState.Success; // (enum member) State.Success = 1
BadState.Fail; // (enum member) State.Fail = 2
const badCheckState = (state: BadState) => {
//
};
badCheckState(100);
//Good ✅
type GoodState = "InProgress" | "Success" | "Fail";
enum GoodState2 {
InProgress = "InProgress",
Success = "Success",
Fail = "Fail",
}
const goodCheckState = (state: GoodState2) => {};
goodCheckState("fsdgfsgf");
export {};
// from: https://www.youtube.com/watch?v=ZCllX1p763U
// @3 - is
type Species = "cat" | "dog";
interface Pet {
species: Species;
}
class Cat implements Pet {
public species: Species = "cat";
public meow(): void {
console.log("Meow");
}
public jump(): void {
console.log("Jumping...");
}
public walk(): void {
console.log("Walking...");
}
}
function petIsCat(pet: Pet): pet is Cat {
return pet.species === "cat";
}
function petIsCatBoolean(pet: Pet): boolean {
return pet.species === "cat";
}
const p: Pet = new Cat();
//Bad ❌
// p.meow(); // ERROR: Property 'meow' does not exist on type 'Pet'.
if (petIsCatBoolean(p)) {
// p.meow(); // ERROR: Property 'meow' does not exist on type 'Pet'.
(p as Cat).meow();
//What if we have many properties? Do you wanna repeat the same casting
//Over and over again...
}
//Good ✅
if (petIsCat(p)) {
p.meow(); // now compiler knows for sure that the variable is of type Cat and it has meow method
}
export {};
// from: https://www.youtube.com/watch?v=ZCllX1p763U
// @4 - satisfies
//Custom interface for rendering images
interface ICustomImage {
data: string;
width: number;
height: number;
}
//Sample of a Custom Image
const myCustomImage: ICustomImage = {
data: "base64",
width: 200,
height: 150,
};
//Image type for the user
type UserImage = string | ICustomImage;
//User interface
interface IUser {
id: number;
firstName: string;
lastName: string;
image: UserImage;
}
//Bad ❌
const badUser: IUser = {
id: 1,
firstName: "Alex",
lastName: "Brooks",
image: "image-url",
};
//Good ✅
const goodUser = {
id: 1,
firstName: "Alex",
lastName: "Brooks",
image: myCustomImage,
} satisfies IUser;
export {};
// from: https://www.youtube.com/watch?v=ZCllX1p763U
// @5 - optional props
type ApiResponse<T> =
| { status: "success"; data: T, timestamp: number }
| { status: "error"; error: string, timestamp: number };
let response: ApiResponse<string> = {
status: "success",
data: "test",
timestamp: 123123123,
};
// clicking one of the fields in the object below, redirect to one of the type definition
let response2: ApiResponse<string> = {
status: "error",
error: "test",
timestamp: 123123123
};
// @6 - types vs interface
// https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment