Skip to content

Instantly share code, notes, and snippets.

@bagaskarala
Last active December 22, 2023 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bagaskarala/94b46d7543a3287406619a2337145aac to your computer and use it in GitHub Desktop.
Save bagaskarala/94b46d7543a3287406619a2337145aac to your computer and use it in GitHub Desktop.
Typescript snippet example
// Select matched object
// Bad implementation
// type ApiResponse {
// state: 'success' | 'failed'
// data?: { name: string }
// error?: { message: string }
// }
type ApiResponseSuccess = {
state: 'success'
data: { name: string }
}
type ApiResponseFailed = {
state: 'failed'
error: { message: string }
}
type ApiResponse = ApiResponseSuccess | ApiResponseFailed
const processResponse = (response: ApiResponse) => {
if (response.state === 'success') {
console.log(response.data.name)
}
if (response.state === 'failed') {
console.log(response.error.message)
}
}
// Narrowing down type
type Person = {
type: 'person'
name: string
age: number
}
type Company = {
type: 'company'
name: string
employeeCount: number
}
type Entity = Company | Person
// Bad implementation
// function isPerson(entity: Entity) {
// return entity.type === 'person'
// }
function isPerson(entity: Entity): entity is Person {
return entity.type === 'person'
}
function checkEntity(entity: Entity) {
if (isPerson(entity)) {
console.log(entity.age)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment