tsconfig.json
{
...
"compilerOptions": {
"strict": true,
...
},
...
}
Enabling strict mode will enable under the hook:
- alwaysStrict
- strictBindCallApply
- strictNullChecks
- strictFunctionTypes
- strictPropertyInitialization
interface Book {
author?: string
numPages: number
price: number
}
// ✅ Article is a Book without a Page
type Article = Omit<Book, 'numPages'>
// ✅ We might need a readonly verison of the Book Type
type ReadonlyBook = Readonly<Book>
// ✅ A Book that must have an author
type NonAnonymousBook = Omit<Book, 'author'> & Required<Pick<Book, 'author'>>
type animals = 'bird' | 'cat' | 'crocodile'
type mamals = Exclude<animals, 'crocodile'>
// 'bird' | 'cat'
// TypeScript ships with the following Mapped Types:
// Omit, Partial, Readonly, Exclude, Extract, NonNullable, ReturnType.
const addNumber = (a: number, b: number) => a + b
// ❌ you are hardcoding the type `number` instead of relying on what the function returns
const processResult = (result: number) => console.log(result)
processResult(addNumber(1, 1))
// ✅ result will be whatever the return type of addNumber function
// no need for us to redefine it
const processResult = (result: ReturnType<typeof addNumber>) => console.log(result)
processResult(addNumber(1, 1))
// Avoid writing several overloads that differ only in trailing parameters
// ❌ instead of this
const Params = {
one: number,
two?: number,
three?: number
}
interface Example {
foo(one: number): number
foo(one: number, two: number): number
foo(one: number, two: number, three: number): number
foo({one, two, three}: Params): number
foo({two: "bla"})
foo(null, "bla")
}
// ❎ do this
interface Example {
foo(one?: number, two?: number, three?: number): number
}
// Avoid writing overloads that differ by type in only one argument type
// ❌ instead of this
interface Example {
foo(one: number): number
foo(one: string): number
}
// ❎ do this
interface Example {
foo(one: number | string): number
}
// ❌ Avoid, parameters types and length are unknown. Return type is any
const onSubmit = (callback: Function) => callback(1, 2, 3)
// ✅ Preferred, the arguments and return type of callback is now clear
const onSubmit = (callback: () => Promise<unknown>) => callback()
// ✅ declare properties as readonly
interface Person {
readonly name: string
readonly age: number
}
// ✅ implicitely declaring a readonly arrays
const x = [1, 2, 3, 4, 5] as const
// ✅ explicitely declaring a readonly array
const y: ReadonlyArray<{ x: number; y: number }> = [{ x: 1, y: 1 }]
interface Address {
street: string
city: string
}
// ✅ converting all the type properties to readonly
type ReadonlyAddress = Readonly<Address>