TypeScript. Basics
3 min readJan 6, 2024
1. Built-in generic types. Utility Types
- Array<T>: Represents an array of elements of type
T
.
let numbers: Array<number> = [1, 2, 3]
- ReadonlyArray<T>: Represents an array of elements of type
T
that cannot be modified.
let readonlyNumbers: ReadonlyArray<number> = [1, 2, 3];
readonlyNumbers.push() // Error
- Promise<T>: Represents an asynchronous operation that returns a value of type
T
.
function fetchData(): Promise<string> {
// ...
}
- Awaited<Type>: Is meant to model operations like
await
inasync
functions.
async function fetchSomething(): Promise<string> {
// Imagine this function fetches data and returns a string
return "some data"
}
type FetchedDataType = Awaited<ReturnType<typeof fetchSomething>>
- Map<K, V>: Represents a collection of key-value pairs with keys of type
K
and values of typeV
.
let map: Map<string, number> = new Map()
- Set<T>: Represents a set of unique values of type
T
.
let set: Set<number> = new Set([1, 2, 3])
- Record<K, T>: A utility type that constructs a type with a set of properties
K
of a given typeT
.
let record: Record<string, number> = { a: 1, b: 2, c: 3 }
- Partial<T>: Constructs a type with all properties of
T
set to optional.
type MyType = {
name: string
age: number
}
type PartialType = Partial<MyType>
// PartialType = {
// name?: string
// age?: number
// }
- Required<T>: Constructs a type with all properties of
T
set to required. The opposite of Partial.
type MyType = {
name?: string
age?: number
}
type RequiredType = Required<MyType>
// RequiredType = {
// name: string
// age: number
// }
- Readonly<T>: Constructs a type with all properties of
T
set to readonly.
type ReadonlyType = Readonly<MyType>
- Pick<T, K>: Constructs a type by picking the set of properties
K
fromT
.
type MyType = {
name: string
age: number
prop1: string
prop2: string
}
type PickedType = Pick<MyType, 'name' | 'age'>
// PickedType = {
// name: string
// age: number
// }
- Omit<T, K>: Constructs a type by omitting the set of properties
K
fromT
. The opposite of Pick.
type MyType = {
name: string
age: number
prop1: string
prop2: string
}
type OmittedType = Omit<MyType, 'name' | 'age'>
// OmittedType = {
// prop1: string
// prop2: string
// }
- NonNullable<T>: Constructs a type by excluding
null
andundefined
fromT
.
type MyType = {
name: string
prop1: null
}
type NonNullableType = NonNullable<MyType>
// NonNullableType = {
// name: string
// }
- ReturnType<Type>: is a utility type that extracts and represents the return type of a function type
Type
.
type MyFunctionType = () => number
type MyReturnType = ReturnType<MyFunctionType> // MyReturnType is number
More info: https://www.typescriptlang.org/docs/handbook/utility-types.html
2. React Component Types
- Function Components
interface MyComponentProps {
message: string
}
const MyComponent: React.FC<MyComponentProps> = ({ message }) => {
return <div>{message}</div>
}
- Class Components
interface MyProps {
message: string
}
interface MyState {
count: number
}
class MyComponent extends React.Component<MyProps, MyState> {
// ...
}
- Typing Event Handlers
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
// ...
}
- Typing Refs
const MyFunctionalComponent: React.FC = () => {
const myRef = useRef<HTMLDivElement>(null)
return <div ref={myRef} />
}
- Typing Children
interface Props {
children: React.ReactNode;
}
const MyComponent: React.FC<Props> = ({ children }) => {
return <div>{children}</div>
}
- Typing Context
interface ContextValue {
authenticated: boolean
user: User | null
}
const MyContext = React.createContext<ContextValue>({
authenticated: false,
user: null,
})
const MyProvider: React.FC = ({ children }) => {
// ...
}
3. Typing HTML Elements and Events
const divElement: HTMLDivElement = document.createElement('div')
const inputElement: HTMLInputElement = document.createElement('input')
const buttonElement: HTMLButtonElement = document.createElement('button')
const selectElement: HTMLSelectElement = document.createElement('select')
const handleClick = (event: MouseEvent) => {
// ...
}
const handleInput = (event: Event) => {
const inputElement = event.target as HTMLInputElement
// ...
}
const handleChange = (event: Event) => {
const selectElement = event.target as HTMLSelectElement
// ...
}
const handleKeyDown = (event: KeyboardEvent) => {
// ...
}
4. Other use cases
type User = {
name: string,
id: number
}
type ActionType = `id_${keyof User}`
type Action<T, K extends keyof T & string> = {
type: ActionType,
payload: T[K],
}
type UpdateNameAction = Action<User, 'name'>
type Animal = {
name: string;
}
type Bear = Animal & {
honey: boolean;
}
function printText(s: string, alignment: "left" | "right" | "center") {
console.log(alignment === 'left')
}