DEV Community

Discussion on: Advanced TypeScript Types cheat sheet (with examples)

Collapse
 
mutterpedro profile image
Pedro Mutter

Congratulations! Really good article, very useful! I would like to add the possibility to create your own type guards on the type guard section, here is an example:

typeguard example

Collapse
 
skye profile image
Skye Wu

i think : obj is ImportantType is ok, but can be more simpler:

function isImportantType(obj: any): boolean {
  return obj.id && obj.requiredFiled;
}
Collapse
 
mutterpedro profile image
Pedro Mutter

But it wouldn't be a type guard though.

Thread Thread
 
skye profile image
Skye Wu

thanks for explain

Collapse
 
toddmath profile image
Todd Matheson

That defeats the purpose of using the type guard altogether. Typescript won’t infer the type from that function. :obj is ImportantType is the what tells typescript what the passed parameters type is. Hence type guard.

Thread Thread
 
skye profile image
Skye Wu

thanks for explain

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Great! A really good example, I will add it to the article.