Last active
December 22, 2023 17:25
-
-
Save bagaskarala/94b46d7543a3287406619a2337145aac to your computer and use it in GitHub Desktop.
Typescript snippet example
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
// 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) | |
} | |
} |
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
// 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