Skip to content

Instantly share code, notes, and snippets.

@d0rsha
Last active July 13, 2023 06:47
Show Gist options
  • Save d0rsha/e051c4f12c9419f4ef8c16b545f9d151 to your computer and use it in GitHub Desktop.
Save d0rsha/e051c4f12c9419f4ef8c16b545f9d151 to your computer and use it in GitHub Desktop.
[TypeScript Anti patterns] Anti patterns for typescript #typescript
// create optional interface
interface Person{
firstName: string;
lastName: string;
}
type Optional<T> = {
[P in keyof T]?: T[P];
};
const partialPerson: Optional<Person> = {};
// Getting the Return Type of a Function with {ReturnType}
const add = (a: number, b: number) => a + b;
const num: ReturnType<typeof add> = 1;
// If we don’t know the exact structure that the object will have, we can use typeof operator as follows:
const person = {
firstName: 'Jane',
lastName: 'Smith',
fullName(firstName: string, lastName: string) {
return `${firstName} ${lastName}`;
}
}
const person2: typeof person = {
firstName: 'Joe',
lastName: 'Smith',
fullName(firstName, lastName) {
return `${firstName} ${lastName}`;
}
}
// We should specify the data types of parameters and return types in our functions like following
type ArithmeticFn = (a: number, b: number) => number
const add: ArithmeticFn = (a: number, b: number): number => a + b;
// Also, once again, we can use typeof to do type inference:
const add = (a: number, b: number): number => a + b;
const subtract: typeof add = (a, b) => a-b
// There are more operators than | when defining types.
const eitherOne: User | Person = {};
// Union
const union: User & Person = {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment