Skip to content

Instantly share code, notes, and snippets.

@jldec
Created August 27, 2024 09:04
Show Gist options
  • Save jldec/edaa4ea91255c054fb0a24863b16068a to your computer and use it in GitHub Desktop.
Save jldec/edaa4ea91255c054fb0a24863b16068a to your computer and use it in GitHub Desktop.
TypeScript type assertions
// https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions
// not to be confused with an "assertion function"
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions
type ObjectType1 = {
prop1: string
}
type ObjectType2 = {
prop1: string
prop2: string
}
const obj1: ObjectType1 = {
prop1: 'string prop for obj1'
}
const obj2: ObjectType2 = {
prop1: 'string prop for obj2',
prop2: 'string prop for obj2'
}
// it's ok to assign an ObjectType2 to an ObjectType1 but not the other way around
let obj3: ObjectType1 = obj2
let obj4: ObjectType2 = obj1
// suppress the error with a type assertion (cast)
// both styles do the same thing but the pointy brackets don't work with JSX
obj4 = obj1 as ObjectType2
obj4 = <ObjectType2>obj1
// accessing an unknown property might work but TypeScript still complains
console.log(obj3.prop2)
// suppress the error with a type assertion
console.log((obj3 as ObjectType2).prop2)
console.log((<ObjectType2>obj3).prop2)
@jldec
Copy link
Author

jldec commented Aug 27, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment