Week 2 Typescript

Michiel van der Gragt
25 Aug 202421:02

Summary

TLDRThis video script introduces TypeScript as a superset of JavaScript with added strict rules for better code behavior. It guides viewers on installing TypeScript and Visual Studio Code, along with essential extensions. The tutorial covers creating a TypeScript file, initializing TypeScript with a config file, defining variables and arrays with specific types, and using interfaces to define object structures. It also explains functions, handling optional properties, and creating custom types. The script concludes with compiling TypeScript to JavaScript.

Takeaways

  • 🌐 **TypeScript Introduction**: TypeScript is described as JavaScript with superpowers, a superset that adds restrictions and strict rules for better code behavior.
  • 🛠️ **Tool Requirements**: To work with TypeScript, the presenter suggests having Visual Studio Code and Node.js installed.
  • 📂 **Project Setup**: The process of setting up a TypeScript project on a desktop involves creating a folder, navigating into it, and opening it in Visual Studio Code.
  • 🔌 **Extensions Recommendation**: For enhanced TypeScript development, extensions like Auto Rename Tag, ES7+, and Prettier are recommended.
  • 📝 **File Creation**: A `.ts` file is created for writing TypeScript code, with `TS` standing for TypeScript.
  • 📥 **TypeScript Installation**: The script explains how to install TypeScript globally using npm on Windows or with `sudo` on a Mac.
  • 🔄 **Initialization**: After installation, TypeScript is initialized to create a `tsconfig.json` file, which manages TypeScript code settings.
  • 🔍 **Type Annotations**: TypeScript allows for the specification of types for variables to ensure type safety and correctness.
  • 📚 **Interfaces**: Interfaces in TypeScript are used to define the structure of objects with specific types for each property.
  • 🔧 **Type Definitions**: Types can be defined for values that can be of multiple types, known as union types, and are used for more complex data structures.
  • 🔄 **Transpilation**: The final TypeScript code is transpiled to JavaScript using the `tsc` command, making it executable in environments that only understand JavaScript.

Q & A

  • What is TypeScript and how does it relate to JavaScript?

    -TypeScript is a superset of JavaScript that adds strict rules and restrictions to help developers write more reliable code. It aims to calm the chaos of unexpected bugs by enforcing type checking.

  • Why might TypeScript be considered as having 'superpowers' over JavaScript?

    -TypeScript is considered to have 'superpowers' because it provides additional features such as static types, which help catch errors at compile time rather than runtime, thus improving code reliability and maintainability.

  • What are the two software requirements mentioned in the script for setting up TypeScript?

    -The two software requirements mentioned are Visual Studio Code and Node.js. Visual Studio Code is the recommended code editor, and Node.js is needed for running JavaScript on the server-side.

  • How do you create a TypeScript file in Visual Studio Code?

    -To create a TypeScript file in Visual Studio Code, open the terminal within the desired directory and type 'code .' to open the directory in Visual Studio Code, then create a new file with a '.ts' extension.

  • What are the three extensions recommended in the script for TypeScript development?

    -The three extensions recommended for TypeScript development are 'Auto Rename Tag', 'ES7+ React/Redux/GraphQL/JS/TS', and 'Prettier - Code formatter'.

  • How do you install TypeScript globally on a Windows machine?

    -On a Windows machine, you install TypeScript globally by running 'npm install -g typescript' in the command prompt.

  • What is a TSConfig file and why is it important?

    -A TSConfig file is a JSON file that helps manage TypeScript code by providing various compiler options such as file inclusion/exclusion, target JavaScript version, and additional checks to enforce code accuracy and strictness.

  • How does TypeScript handle variable typing compared to JavaScript?

    -TypeScript requires explicit typing of variables, which helps catch type-related errors at compile time. JavaScript, on the other hand, infers types dynamically at runtime, which can lead to unexpected bugs.

  • What is an interface in TypeScript and how is it used?

    -An interface in TypeScript is a way to define the shape of an object, specifying the types of its properties. It is used to ensure that objects conform to a specific structure.

  • How can you make a property optional in an interface?

    -You can make a property optional in an interface by adding a question mark (?) after the property name, indicating that the property is not required.

  • How do you compile TypeScript code into JavaScript?

    -To compile TypeScript code into JavaScript, you use the TypeScript compiler by running 'tsc' in the terminal within the directory containing the TypeScript files.

Outlines

00:00

🔧 Introduction to TypeScript

The script begins by introducing TypeScript as a solution to JavaScript's unpredictable bugs. It's described as a superset of JavaScript that adds strict rules to ensure more reliable code behavior. An analogy is used to explain TypeScript's role in maintaining order, similar to not allowing dessert before dinner. The presenter suggests installing Visual Studio Code and Node.js as prerequisites. They demonstrate how to create a TypeScript file and emphasize the importance of certain extensions for a better coding experience.

05:01

🛠️ Installing and Configuring TypeScript

The second paragraph explains the process of installing TypeScript on both Windows and Mac systems. It details the steps to initialize TypeScript, which includes creating a TS config file—a JSON file that manages TypeScript code with various compiler options. The presenter discusses the purpose of this configuration file, which acts as a roadmap for the compiler, setting rules for code compilation.

10:01

📚 Understanding TypeScript Variables and Types

Here, the focus is on creating variables in TypeScript and how it differs from JavaScript. TypeScript is praised for its ability to accurately infer types. Examples are given to show how TypeScript can define variables as specific types, such as numbers, strings, or booleans. The concept of 'any' is introduced as a type that can hold any value, but its use is discouraged for maintaining type safety.

15:02

🎯 Functions and Defining Types with Interfaces

The script moves on to discuss functions in TypeScript. An example function 'addValues' is created, which adds two values. The presenter then shows how to run TypeScript files using 'ts-node'. The concept of defining object structures using interfaces is introduced, emphasizing the importance of explicitly defining types to ensure type safety and avoid runtime errors.

20:04

🔄 Advanced TypeScript Features: Union Types and Type Conversion

The final paragraph covers advanced TypeScript features like union types, which allow a variable to be one of several types. The presenter demonstrates how to define a password field that can be either a number or a string. They also explain how to convert types and the process of compiling TypeScript back into JavaScript, which is the final output for execution.

Mindmap

Keywords

💡TypeScript

TypeScript is a superset of JavaScript that adds optional static types to the language. In the context of the video, TypeScript is presented as a way to add 'superpowers' to JavaScript by imposing strict rules and restrictions to ensure more predictable and maintainable code. The script uses the analogy of TypeScript being like a parent that won't let you have dessert before vegetables, enforcing a certain order and correctness in how code is written.

💡JavaScript

JavaScript is a high-level, often just-in-time compiled, programming language that is widely used for enhancing web pages with interactive elements. The video script positions JavaScript as the base language upon which TypeScript builds, adding type safety and other features to help developers catch errors at compile time rather than at runtime.

💡Visual Studio Code

Visual Studio Code, often abbreviated as VS Code, is a popular source code editor developed by Microsoft. The script mentions VS Code as the recommended integrated development environment (IDE) for working with TypeScript, highlighting its usefulness for developers looking to take advantage of TypeScript's features.

💡Node.js

Node.js is a JavaScript runtime that allows developers to execute JavaScript on the server side. The script instructs viewers to install Node.js from nodejs.org, which is necessary for running TypeScript projects on a local machine, separate from a web browser environment.

💡Extensions

Extensions in the context of the video refer to additional features or plugins that can be added to an IDE like Visual Studio Code to enhance its functionality. The script suggests installing specific extensions such as 'Auto Rename Tag', 'ES7+', and 'Prettier' to improve the TypeScript development experience.

💡TSConfig

The TSConfig file is a JSON file that contains the compiler options for TypeScript projects. The video script explains that this file is crucial for managing TypeScript code as it includes settings for compiler options, such as which files to include or exclude, the target JavaScript version, and how strict the type checking should be.

💡Type Annotations

Type annotations in TypeScript are used to explicitly specify the types of variables, function return values, and more. The script gives examples of how to annotate variables with types like 'number', 'string', and 'boolean', which helps TypeScript's compiler to enforce type correctness.

💡Interfaces

Interfaces in TypeScript are used to define the shape of an object, specifying the types of its properties. The video script uses the example of a 'Car' interface to illustrate how interfaces can be used to ensure that objects conform to a specific structure, which is a powerful way to maintain consistency across a codebase.

💡Type Definitions

Type definitions in TypeScript are used to define the structure of a value of any type. The script contrasts interfaces, which are used for object types, with types, which can be used for primitive data types or unions. An example given is defining a 'PasswordFieldType' that can be a number or a string.

💡Union Types

Union types in TypeScript allow a value to be one of several types. The script uses a password field as an example where the type could be either a number or a string, demonstrating how union types can represent values that could be one of several types.

💡Transpilation

Transpilation is the process of converting code from one language (or version) to another. In the script, it's mentioned that after writing TypeScript code, you can use the 'tsc' command to transpile it into JavaScript code, which can then be executed in a JavaScript runtime like Node.js.

Highlights

JavaScript bugs can cause unexpected issues, and TypeScript helps mitigate these by adding stricter rules to JavaScript.

TypeScript is a superset of JavaScript that introduces restrictions to ensure better code behavior and predictability.

TypeScript enforces rules, such as ensuring that you 'eat your vegetables' (follow proper code structure) before 'dessert' (the final output).

To get started with TypeScript, you need to install Visual Studio Code and Node.js, and ensure you have essential extensions like Auto Rename Tag, ES7+ Snippets, and Prettier for cleaner code.

TypeScript requires installing and initializing it via the terminal using npm install commands, especially different for Mac vs Windows environments.

TypeScript's `tsconfig.json` helps manage configuration settings for compiling TypeScript code, setting parameters like the target JavaScript version and compiler checks.

TypeScript enhances variable declarations by allowing you to specify types explicitly, such as number, string, and boolean, for more predictable code.

You can declare arrays with specific types in TypeScript, ensuring the array only contains elements of a given type, avoiding type mismatches.

Functions in TypeScript can have specific types for their parameters and return values, ensuring they always behave as expected.

TypeScript allows the creation of interfaces that define the structure of objects, including data types for properties and optional fields.

Interfaces in TypeScript can include methods, and those methods must adhere to the defined function signatures and return types, like void for non-returning functions.

TypeScript supports unions, where variables can be multiple types (e.g., a password can be either a number or a string), increasing flexibility in code.

The difference between interfaces and types is clarified: interfaces are primarily used for objects, while types are used for union types and other constructs.

TypeScript code can be compiled into JavaScript using the `TSC` command, converting strongly typed code into plain JavaScript.

Using TypeScript ensures code is more maintainable, predictable, and less prone to runtime errors due to its strong typing system and compilation checks.

Transcripts

play00:03

hi there you recognize those moments

play00:06

when JavaScript is just throwing a

play00:08

tantrum those unexpected bugs that pop

play00:11

up when you think everything should be

play00:14

working what if I told you there's a way

play00:16

to calm that chaos introducing

play00:20

typescripts so I hear you thinking well

play00:23

what is typescript well think of

play00:26

typescript as JavaScript with superpower

play00:30

it's a super set of JavaScript which

play00:32

basically means it adds some actually

play00:34

restrictions some strict rules so your

play00:37

code behaves

play00:39

well let me give you an

play00:41

example JavaScript might let you eat

play00:44

your

play00:45

dessert before your main

play00:47

meal well typescript will not let you do

play00:49

that it will check your plate have you

play00:52

eaten your vegetables is your plate

play00:54

empty yes well then you can have your

play00:57

dessert

play01:00

so basically typescript checks the rules

play01:03

are you following the rules yet all

play01:05

right so now that you um know that we're

play01:08

going to use with typescript and that

play01:09

typescript is just making JavaScript

play01:11

better um make sure that you have

play01:14

installed two things on your

play01:16

computer Visual Studio

play01:19

code and note

play01:21

JS Visual Studio code you probably

play01:24

already have nodejs just go to

play01:26

nodejs.org and get it installed there

play01:30

I'm on a Mech right now

play01:33

and I'm going to show you how to get

play01:36

started here so first of all on my

play01:39

desktop I have um a folder called

play01:43

typescript and I'm going

play01:46

to let's

play01:50

see I'm going to open up a terminal here

play01:54

we go terminal I'm going to CD into this

play01:58

folder

play02:00

change directory I'm in the directory

play02:02

now and I'll type code and then the dot

play02:05

so it opens up inside this directory

play02:07

inside Visual Studio

play02:09

code by the way this does not work

play02:12

automatically on the Mac um you would

play02:17

have to go into Visual Studio code and

play02:20

go to the command pellet uh so shift

play02:24

command

play02:25

p and you would have to install it like

play02:28

this all right

play02:31

okay anyways so let's go back to where I

play02:34

was here I close this here um code and

play02:40

it opens it up inside a visual studio

play02:43

code all right great you can see it's

play02:46

right here um also just so you know make

play02:49

sure that you have these inst extensions

play02:52

installed for me uh Auto rename tag I

play02:55

mean you don't have to install them I

play02:57

just think they're very good to use um

play02:59

that is is if you have a beginning tag

play03:01

and a closing tag and you change the

play03:03

beginning tag it automatically changes

play03:05

the closing tag then es7 plus and

play03:10

prettier okay so install those two if

play03:14

you want to read more about them you

play03:15

click on one here and you can see you

play03:18

can read all it does okay um same for

play03:23

pretty here make sure code is

play03:26

pretty yeah easier to read make sure you

play03:29

install at least these three probably

play03:32

you have your own preferences all

play03:34

perfectly

play03:35

fine okay good um so let's go back here

play03:41

and just so you know um for

play03:45

typescripts uh and javascripts

play03:47

JavaScript you can run either in the

play03:50

browser using an HTML uh file uh or just

play03:54

like we're going to do now we're going

play03:56

to run it in a note okay

play04:13

all right to get started uh we first

play04:16

going to create a file uh here we go and

play04:19

I'm going to say type no I'm going to

play04:23

call it

play04:24

tutorial. TS Ts for typescripts you can

play04:27

see if I type in jss it's a j script

play04:30

file and TS is for a typescript file

play04:33

there we go um we're going to write all

play04:36

our code in here but to be able to do so

play04:39

we need to install

play04:42

typescripts all right so to install

play04:45

typescript on a Windows uh machine you

play04:48

do npm

play04:51

install globally type

play04:55

script you will see it doesn't work on

play04:57

the Mac clear

play05:00

instead I would have to do pseudo npm

play05:04

install globally type

play05:08

script there with the password for the

play05:11

mac and it would install it that way

play05:18

okay now that we have typescript

play05:21

installed we should also initialize it

play05:24

we did it as follows follows uh on a

play05:27

Windows machine you do TS see typescript

play05:31

in it or as I am on a Mac I have

play05:35

to add Pudo in front of

play05:41

it

play05:43

enter and here we go we have our TS

play05:46

config file which is a Json

play05:51

file this file will help us to manage

play05:54

our typescript code it has a bunch of

play05:56

config configuration settings inside of

play06:00

it the file includes settings for

play06:04

various compiler options such as which

play06:07

files to include or exclude the target

play06:11

JavaScript version you want your

play06:13

typescript to run with and additional

play06:16

checks to tell your file how

play06:21

um accurate you want to be how strict

play06:23

you want it to be so basically it's a

play06:25

road map telling your compiler which

play06:28

settings to follow for now we're going

play06:30

to leave all the settings the way they

play06:32

are all right so now we're in the file

play06:35

and we all know how to create a variable

play06:37

for example let H equals

play06:41

45 now typescript is already doing quite

play06:44

a good job guessing what H is it is a

play06:47

number that is right but we actually

play06:50

want to tell we want to be accurate in

play06:53

saying what it

play06:54

returns so this will return a number

play06:59

then

play07:00

let job

play07:02

equals a

play07:05

teacher again JavaScript will guess what

play07:08

it is it's a string it is correct this

play07:11

is a string

play07:13

indeed let is

play07:20

fanastic equals to true what is this a

play07:24

bullion will touch guess it right yes

play07:27

it's a bullion this will return a

play07:32

Boolean okay so now I've added three

play07:34

more lines uh here for example let ages

play07:38

equals and it's an array of four numbers

play07:41

so what will this return this will

play07:44

return

play07:48

an

play07:50

array

play07:51

of

play07:53

numbers okay if I would say this is an

play07:57

array of strings you say this is not

play08:00

accepted the type number is not

play08:02

assignable to a type string unless of

play08:04

course I would turn these into

play08:12

Strings it would

play08:14

work in that case number would not work

play08:20

let's change it back to

play08:25

number in some cases you're a bit sloppy

play08:28

and you would not know what to

play08:30

return then you could always type in

play08:34

any or here is an array with a string a

play08:38

number in a

play08:40

Boolean so you can say it's allowed to

play08:44

return anything inside this

play08:47

array generally try to avoid any okay

play08:50

now let's move on and uh look let's look

play08:53

at

play08:54

functions so I'm going to create a

play08:58

function called add

play09:00

values and it's going to be an arrow

play09:04

function

play09:06

there and the arrow function accepts two

play09:10

values A and B and it's

play09:14

returning A and

play09:18

B There we

play09:20

go now what happens if I console log

play09:24

this so I'm going to console log this

play09:27

function here values

play09:33

there and I'm going to because right now

play09:37

A and B are um defined as any so I

play09:44

should be able to just call my

play09:51

name so a equals and b equals so

play09:55

together it should

play09:58

be now what I should also do is to

play10:01

specify that a is a string and B is a

play10:05

string yeah a is of type string BS of

play10:08

type

play10:09

string then I want to check this file to

play10:12

see if the console log is showing me the

play10:15

same the right value

play10:18

say to do that I am just going to

play10:22

install a package called TS node so I

play10:27

can just run this F file in the

play10:39

terminal and

play10:41

clear so now when I say TS

play10:44

node

play10:46

tutorial. TS I should

play10:52

get and there we go so a is of type

play10:55

string and B is of type string and the

play10:57

return is also a string

play11:02

so when I now save it and I run it

play11:05

again it's correct if I want this to be

play11:09

numbers let's say

play11:14

40

play11:15

and five those are two numbers I have to

play11:18

change this into a number that's of type

play11:21

number B is of type number and our

play11:24

return is also a number save this run it

play11:28

again

play11:30

and you see it's 45 which is

play11:33

correct okay now let's move on on how we

play11:36

Define objects and types

play11:41

ourselves so look at this object it has

play11:44

an ID a model and a year yeah the car

play11:49

has an ID a model and the year

play11:52

now um T is already doing a good job it

play11:55

says ID is probably a number the model

play11:59

is a string correct and here is also

play12:02

number but we shouldn't do this we

play12:03

shouldn't let him assume so we should

play12:06

Define the object by using an

play12:15

interface so the

play12:17

interface sort of

play12:19

defines the typ script for the object so

play12:23

we're going to include these inside the

play12:26

interface uh and let's call the

play12:28

interface by the way

play12:30

car

play12:35

interace and we add this but instead of

play12:38

the values we're going to call say the

play12:41

type so this is of type number this is

play12:44

of type

play12:47

string and the last one is also of type

play12:52

number so now we can use this

play12:55

interface right here so we can say

play12:59

car is of

play13:01

type

play13:03

car

play13:07

interface this means if I change this to

play13:09

for example a string or a

play13:15

uh yeah just a string for example it's

play13:19

giving me an error here because this

play13:20

should be a

play13:22

number now what happens if there's for

play13:26

example no age then I am getting an

play13:29

error here because it's missing the year

play13:34

to make this optional because these are

play13:36

not optional at the moment all I have to

play13:38

do is add a question mark behind it

play13:42

okay so now that became

play13:47

optional what I can do is I can console

play13:50

log for example car

play13:54

dot

play13:56

model and if I now check this

play14:01

I get

play14:02

Mercedes but if I get card of year which

play14:05

I have not

play14:07

defined I

play14:09

get

play14:11

undefined okay can you see that

play14:15

undefined um

play14:19

clear so I could

play14:22

say

play14:24

um

play14:27

if car

play14:32

dot if there is no car

play14:36

doe

play14:38

then I can console

play14:43

log um

play14:46

no year for this

play14:55

car else

play15:01

I can console look

play15:06

this there we go let's see if it

play15:11

works oh

play15:14

card car

play15:18

oh there we go

play15:23

clear no year for this car okay but if I

play15:28

addit

play15:30

year

play15:34

2008 I'm going do it again I do get the

play15:38

year all right now let's add a function

play15:41

to this um interface so we could say

play15:45

it's a function where it has um uh color

play16:01

and all we do is we're going to on

play16:06

solo the um yeah what should we say uh

play16:11

gradients I don't

play16:13

know so we're going

play16:17

to gradient just a word okay um now this

play16:22

actually not

play16:23

defined okay um it doesn't exist in the

play16:27

car interface we should actually added

play16:30

added here so we're going to add the

play16:33

function

play16:34

here

play16:36

um and this is actually not going to

play16:40

return anything it's just going to

play16:42

console Lo so void means not returning

play16:46

anything and here then we're going

play16:50

to add the

play16:55

um

play16:56

gradient and the gradient is going to be

play16:59

of a type

play17:01

string like that now there's

play17:06

actually you could add it add the same

play17:09

thing here but you don't have to it's

play17:11

already defined here

play17:15

okay so let's see now let's check the

play17:19

car car

play17:22

dot color and the color is black

play17:29

car. color and we're going to send

play17:33

black okay that's the

play17:37

parameter

play17:39

save and check it out black all right

play17:43

now let's move on to the next step let's

play17:45

say I

play17:47

want um to check

play17:51

a password I don't

play17:53

know

play17:57

um where

play18:01

the

play18:04

code comes in as a

play18:08

parameter and I'm going to

play18:11

console log and then maybe it's the

play18:18

um

play18:26

password and let's the code for the

play18:30

password

play18:32

okay

play18:34

um now of

play18:36

course what is code

play18:39

well let's say the

play18:42

password would

play18:44

be uh 1 two three four

play18:49

five okay then in that case the code is

play18:55

if type

play18:57

number right

play18:59

but a password is not always a

play19:03

number sometimes it's a number

play19:06

or let's see it could even

play19:09

be a

play19:11

string okay in that

play19:16

case Hello would be

play19:20

accepted this is called a

play19:23

union and well with

play19:27

um objects we've kind of used

play19:30

interfaces but um when it's aligned like

play19:33

this we will create types instead okay

play19:37

so interface are use for objects uh and

play19:40

here we will use a type instead so we

play19:43

could for example set type here and we

play19:46

can call it

play19:50

password field

play19:54

type and we could copy these

play20:00

there and place them

play20:03

there and then instead here we could

play20:07

type in

play20:11

password field type like so great okay

play20:17

so we have looked at how to install

play20:19

typescript uh we have looked at how to

play20:23

make them type specific we have looked

play20:25

at

play20:26

interfaces um and we l have looked at

play20:30

how to create specific types um

play20:35

now if you want to turn this now into a

play20:38

JavaScript code all you have top type is

play20:42

TSC and you see that

play20:46

the um code that we have just created

play20:50

here is now a JavaScript

play20:54

code

play20:57

great thank you for listening listening

play20:59

and see you in the next lesson

Rate This

5.0 / 5 (0 votes)

Ähnliche Tags
TypeScriptJavaScriptDevelopmentStrict TypesError PreventionCode QualityProgrammingIDE ToolsVisual Studio CodeType Checking
Benötigen Sie eine Zusammenfassung auf Englisch?