TypeScript
Best practice-ek
Kerüld az any-t, használd a type inference-t, bontsd a típusokat, és tanuld meg a utility type-okat.
Best practice-ek
1) Ne használd az any-t
function processData(data: { value: number }) {
return data.value * 2
}Ha ismeretlen:
function processInput(input: unknown) {
if (typeof input === "number") return input * 2
throw new Error("Nem szám típusú input")
}2) Type inference, ahol lehet
const name = "Adam"
const numbers = [1, 2, 3]
const isActive = true3) Kis, fókuszált típusok
interface Address {
street: string
city: string
country: string
}
interface UserRole {
role: "admin" | "editor" | "viewer"
permissions: string[]
}
interface User {
id: number
name: string
email: string
address: Address
auth: UserRole
createdAt: Date
}4) Beszédes nevek
type NullableString = string | null
type PersonBasicInfo = { name: string; age: number }5) Utility type-ok
interface User {
id: number
name: string
email: string
password: string
}
type UpdateUserDto = Partial<User>
type StrictUser = Required<User>
type PublicUser = Pick<User, "id" | "name">
type SafeUser = Omit<User, "password">
type ImmutableUser = Readonly<User>
type UserMap = Record<string, User>6) Strict mód
{
"compilerOptions": {
"strict": true
}
}