Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Understanding TypeScript
Debbie O'Brien
Debbie O'Brien

Posted on • Originally published atdebbie.codes

     

Understanding TypeScript

TypeScript is a superset of JavaScript. Any types that are added are not part of the final bundle so really TypeScript is there to make your life easier as a developer. It took me years to accept TypeScript. I always wanted to learn it. It was on my long list of todos but I found it complicated and unnecessary and therefore chose not to prioritize it and most importantly not to use it in any of my projects.

Then it got forced upon me and I had no choice but to learn it while at the same time learning a new framework. That was very hard indeed as I wasn't sure if I was learning something React or something TypeScript. Separating the two would have been a whole lot easier.

Why TypeScript?

But I have to say that once you understand even some of the basics of TypeScript and start to use it in your code it really does make your life easier.

TypeScript is not there to complicate things but to help you not make mistakes. Yes it will scream at you and underline everything in red but it's telling you there is a problem and that if you don't fix it then probably something will break either now or in the future. This is actually really helpful and prevents bugs.

In JavaScript we would just allow anything to happen and fix it later which is never a good idea really. I actually believe that TypeScript should be introduced early in the learning of JavaScript cause trust me, once you use it you won't go back and today more and more codebases are being rewritten in TypeScript so it is by far the future.

What exactly does TypeScript do?

TypeScript is about checking your types. What do I mean by that? When you have props that you pass down into your components, for example a name prop then this prop should only accept a string. If someone passes it a number then TypeScript will simply not allow it as it checks the types and a number is not the same type as a string. We basically need to define these types when we are passing our props.

constButton=(props:{buttonText:string})=>({<button>{props.buttonText}</button>})
Enter fullscreen modeExit fullscreen mode

In the above example we pass down props and use the semicolon to define the props. The props are added as an object with the name of the prop followed by a semicolon and the type the prop is allowed to be, which in this case is a string.

Defining Types

In this post I will be using Types instead ofInterfaces which are very similar but have some small differences. There is no right or wrong here so use whatever works best for you.

Types can be defined as any of the primitive values:

  • string
  • number
  • boolean
  • [] an array
  • string[], an array of strings (change to number for an array of numbers etc)
  • "primary" | "secondary", set a specific value
  • {}, any type of object

Defining Object Types

You can get even deeper here and define the shape of an object, for example an object that takes an id of string and a title of string or an array of object types

typeItems{id:string,title:string}[]
Enter fullscreen modeExit fullscreen mode

This can also be cleaned up further by creating a type of item an then passing that to the array

typeItem={id:stringtitle:string}typeComponentProps={item:itemitems:items}
Enter fullscreen modeExit fullscreen mode

Defining Array Types

We can define an array where all keys have to be a number and the value has to be a string

typeItems={[key:number]:string}
Enter fullscreen modeExit fullscreen mode

Or we could make all keys a string and the value has to be of the type Item which was previously defined.

typeItems={[key:string]:Item}
Enter fullscreen modeExit fullscreen mode

This is a pretty simple way to define the props but you can imagine it getting very hard to manage if there were multiple props so adding the types inline might become a nightmare. This is one of the main reasons why we separate the props

Defining Function Types

You can also define types for functions:

Function takes no arguments and does not return anything.

typeButtonProps={onHover:()=>void}
Enter fullscreen modeExit fullscreen mode

Passes in the id of type number and returns nothing, eg undefined

typeButtonProps={onChange:(id:number)=>void}
Enter fullscreen modeExit fullscreen mode

Takes an event that is based on clicking the button and returns nothing. Notice the<HTMLButtonElement>, this means pass in all the available props that the HTML Button provides so it knows you might want to have access toevent.target for example.

typeButtonProps={onClick(event:React.MouseEvent<HTMLButtonElement>):void}
Enter fullscreen modeExit fullscreen mode

When creating functions we can even define the types of what gets passed in as well as what gets returned. However TypeScript is clever enough that it knows if you pass in a as a number and b as a number and you and you return a + b then the return value will be a number so there is not need to define that.

constadd=(a:number,b:number):number=>{returna+b}
Enter fullscreen modeExit fullscreen mode

Separating your Types

We previously added our button with the buttonText prop containing the type of string. If our button has more types this would be really hard to maintain. This is one reason why we separate our types from here but also if we do separate them we can then export them and use them in other components.

From this:

constButton=(props:{buttonText:string})=>({<button>{props.buttonText}</button>})
Enter fullscreen modeExit fullscreen mode

To this:

exporttypeButtonProps={buttonText:string}constButton=(props:ButtonProps)=>({<button>{props.buttonText}</button>})
Enter fullscreen modeExit fullscreen mode

Again we can improve it further by using the names of the props instead of using the props keyword and adding them in curly brackets to destructure them.

exporttypeButtonProps={buttonText:string}constButton=({buttonText}:ButtonProps)=>({<button>{buttonText}</button>})
Enter fullscreen modeExit fullscreen mode

Optional Props

To make props optional we can add a question mark to the end of the type. TypeScript will then only check it's type if it is passed in.

exporttypeButtonProps={buttonText:stringvariation?:'primary'|'secondary'}constButton=({buttonText}:ButtonProps)=>({<button>{buttonText}</button>})// orconstButton=({buttonText,variation}:ButtonProps)=>({<buttonvariation="primary">{buttonText}</button>})
Enter fullscreen modeExit fullscreen mode

Improving your Props with Comments

Comments are a great way to help others understand what your props are for.

exporttypeButtonProps={/**   * a text for the button   */buttonText:string/**   * the variation of the button   */variation?:'primary'|'secondary'}constButton=({buttonText,variation}:ButtonProps)=>({<buttonvariation="primary">{buttonText}</button>})
Enter fullscreen modeExit fullscreen mode

Adding default Values

Default values can be added to your props by giving it a value as you pass it into the function. Then if someone doesn't define a value for that prop the default will be used.

exporttypeButtonProps={/**   * a text for the button   */buttonText:string/**   * the variation of the button   */variation?:'primary'|'secondary'}// add to cart is the default value of the button textconstButton=({buttonText="add to cart",variation}:ButtonProps)=>({<buttonvariation="primary">{buttonText}</button>})
Enter fullscreen modeExit fullscreen mode

Conclusion

TypeScript might take a bit of extra work at the start as you define your types but that little bit of extra work can really save you some time later on. I highly recommend giving it a try and just starting to slowly introduce it in your codebases.

Useful Links

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
debs_obrien profile image
Debbie O'Brien
Principal Technical Program Manager at Microsoft, speaker, writer, teacher, open source contributor, playwright, vue, nuxt, react
  • Location
    Spain
  • Education
    Post Grad in Spanish, Frontend Tech Degree at OpenClassrooms, Fullstack Tech Degree at Treehouse
  • Work
    Principal Technical Program manager at Microsoft
  • Joined

hey, thanks for the reply and detailed answer. looks good. I still havent dived into intrinsicElements yet so will take a look at them. And you're right. I need to use children more. My next post will be on children. As for variation yeah looks good with the btn- which makes it clear why it's there. My quick example is probably not that useful and I do have it in production with a function that creates the classname depending on the prop passed in but that was taking it one step further. so much to learn...... :) thanks again

CollapseExpand
 
rammina profile image
Rammina
A full-stack developer who is passionate for projects that have user value.I also love to exchange my learnings with fellow developers.
  • Location
    Remote
  • Education
    Thomas Edison State University
  • Work
    Full-stack Web Developer | Writer | Educator
  • Joined

Great, well-written guide on how to get a beginner started on Typescript. I'm just happy to see Typescript getting the love it deserves.

I would like to add to this discussion, some case scenarios in which Typescript should NOT be used because of its certain downsides:
dev.to/rammina/downsides-of-typesc...

CollapseExpand
 
debs_obrien profile image
Debbie O'Brien
Principal Technical Program Manager at Microsoft, speaker, writer, teacher, open source contributor, playwright, vue, nuxt, react
  • Location
    Spain
  • Education
    Post Grad in Spanish, Frontend Tech Degree at OpenClassrooms, Fullstack Tech Degree at Treehouse
  • Work
    Principal Technical Program manager at Microsoft
  • Joined

great thanks. will check it out

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Principal Technical Program Manager at Microsoft, speaker, writer, teacher, open source contributor, playwright, vue, nuxt, react
  • Location
    Spain
  • Education
    Post Grad in Spanish, Frontend Tech Degree at OpenClassrooms, Fullstack Tech Degree at Treehouse
  • Work
    Principal Technical Program manager at Microsoft
  • Joined

More fromDebbie O'Brien

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp