Last active
July 13, 2023 06:47
-
-
Save d0rsha/e051c4f12c9419f4ef8c16b545f9d151 to your computer and use it in GitHub Desktop.
[TypeScript Anti patterns] Anti patterns for typescript #typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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