No BS TS #1 - Typescript Setup & Everyday Types

Jack Herrington
19 Apr 202113:10

Summary

TLDRIn this informative video, the host introduces TypeScript to JavaScript developers, highlighting its benefits in catching common bugs and speeding up coding by providing type safety and immediate feedback. The tutorial begins with a simple JavaScript example, transitions into TypeScript, and demonstrates how TypeScript's static typing system helps identify and fix errors. The video covers basic types, arrays, objects, interfaces, and type inference, offering practical insights into TypeScript's features and how they enhance the development process.

Takeaways

  • 🔍 TypeScript is a superset of JavaScript that adds static types to help catch errors at compile time, such as null or undefined values and incorrect function parameters.
  • 🐛 TypeScript can help developers write code faster by providing immediate feedback on type mismatches and missing fields.
  • 📂 To start with TypeScript, create a directory for the project, use `yarn init` to generate a `package.json`, and add TypeScript and `ts-node` in development mode.
  • 📃 Convert a JavaScript file to TypeScript by changing the extension from `.js` to `.ts`, which allows TypeScript to provide type checking.
  • 🛠 TypeScript infers types automatically, and you can manually specify types using a colon followed by the type name (e.g., `: boolean`).
  • 🔧 TypeScript helps identify and fix bugs, such as when trying to concatenate a string with a boolean value.
  • 📊 Arrays in TypeScript can be typed using brackets to denote an array of a certain type, or by using the generic type with less than and greater than symbols (e.g., `Array<number>`).
  • 🔗 Interfaces in TypeScript allow you to define a contract for the shape of an object, which can be reused throughout the codebase.
  • 🔄 TypeScript supports tuples for fixed-size, heterogeneous arrays, and utility types like `record` for defining key-value pairs with specific types.
  • 🏷️ TypeScript's type system does not restrict the API design but helps enforce and hint the expected types to other developers.
  • 🔄 Conditionals and loops in TypeScript work similarly to JavaScript, but TypeScript provides type inference for variables within these constructs.
  • 🎥 TypeScript can infer types in functions and array operations, and it can catch mismatches in return types or operations.

Q & A

  • What is the main purpose of the 'No BS TS' series?

    -The main purpose of the 'No BS TS' series is to provide 5 to 15 minute introductions for learning TypeScript, particularly for those with a JavaScript background, at their own pace.

  • What are the two primary reasons for using TypeScript?

    -The two primary reasons for using TypeScript are to prevent runtime errors by catching issues such as calling methods on null or undefined values and to help developers code faster by providing immediate feedback on correct fields and types.

  • How does TypeScript help in debugging JavaScript code?

    -TypeScript helps in debugging by providing type checking that catches errors such as incorrect type assignments, missing fields, or incorrect field names before the code is run.

  • How does the speaker start their TypeScript journey in the video?

    -The speaker starts by creating a directory called 'ts basics' and then initializes a TypeScript project using 'yarn init', adds TypeScript and 'ts-node' in development mode, and initializes a TypeScript configuration file.

  • What is the issue the speaker identifies in their JavaScript code?

    -The issue identified is that the speaker mistakenly adds a string to a boolean value, resulting in an unintended coercion of the boolean to a string.

  • How does TypeScript handle the error in the basics.js file?

    -TypeScript catches the error by indicating that the type 'string' is not assignable to the type 'boolean', thus preventing the code from compiling until the issue is resolved.

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

    -An interface in TypeScript is a structure that defines the shape of an object, including its properties and methods. It is used to enforce a specific type structure and can be reused across the codebase to maintain consistency.

  • How does TypeScript handle arrays?

    -TypeScript handles arrays by allowing the specification of the type within brackets. It also supports generic types for arrays and can enforce that elements of the array are of the specified type.

  • What is a tuple in TypeScript?

    -A tuple in TypeScript is a structure that allows the definition of an array with known element types, but with a fixed number of elements, each potentially of a different type.

  • How does TypeScript work with objects as maps?

    -TypeScript works with objects as maps using the 'record' utility type, which allows the definition of a type for keys and values separately, enabling the creation of a map-like structure with typed keys and values.

  • How does TypeScript affect the way conditionals and loops are written?

    -TypeScript does not change the way conditionals and loops are written in terms of logic, but it does provide type checking and inference for variables within those structures, ensuring type safety and preventing type-related errors.

  • What is the speaker's conclusion about TypeScript in relation to API design?

    -The speaker concludes that TypeScript does not restrict API design but rather enforces and hints at the intended type structure, allowing developers to create APIs with the flexibility needed while maintaining type safety.

Outlines

00:00

🚀 Introduction to TypeScript Basics

The video introduces the series 'No BS TS' with the aim of providing 5-15 minute introductions to TypeScript, particularly for those with a JavaScript background. It highlights the two main reasons for using TypeScript: to prevent common runtime errors such as null or undefined value access, and to enhance coding speed by providing immediate feedback on field correctness and completeness. The video then demonstrates how TypeScript can help identify a bug in JavaScript by showing the process of setting up a TypeScript environment and converting a JavaScript file to TypeScript, which immediately flags the type error.

05:01

📚 Understanding TypeScript Types

This paragraph delves into the different types in TypeScript, starting with basic types like string and number, and moving on to more complex ones like regex. It explains how TypeScript infers types and how to explicitly define them using the colon syntax. The video also covers arrays, tuples, and objects, showing how TypeScript enforces type safety while remaining flexible. It introduces interfaces and the concept of reusing type definitions, and briefly touches on how TypeScript works with maps and conditionals, emphasizing that it does not change the logic of these constructs but rather enhances type safety during variable declarations and iterations.

10:02

🔍 Advanced Typing with TypeScript

The final paragraph of the video focuses on advanced typing techniques in TypeScript, including the use of the 'record' utility type for creating key-value pairs and the handling of conditionals and loops. It emphasizes that TypeScript's type system does not alter the fundamental logic of JavaScript but enhances it with type safety. The video also discusses how TypeScript infers types in for-loops and map functions, and how it can be adjusted to correct type mismatches. The video concludes with a teaser for the next episode, which will cover type definitions for functions, and encourages viewers to like, subscribe, and turn on notifications for the series.

Mindmap

Keywords

💡TypeScript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static types to the language, which can help catch errors during development and improve code maintainability. In the video, TypeScript is introduced as a tool to save developers from runtime errors and to enhance coding speed by providing type safety and autocompletion features.

💡Type Checking

Type checking is the process of verifying and enforcing the types of variables in a program. TypeScript uses type checking to ensure that variables are used consistently with their intended data types, which helps prevent type-related bugs. In the video, the host demonstrates how TypeScript's type checking can catch a mistake where a boolean value was incorrectly used in a string context.

💡Type Inference

Type inference is the process by which TypeScript automatically determines the type of a value based on its usage in the code. This feature allows developers to write cleaner code without explicitly declaring types for every variable, as TypeScript can deduce the correct type from the context. In the video, the host shows how TypeScript infers the type of 'hasLoggedIn' as boolean and catches a type mismatch error.

💡Interfaces

Interfaces in TypeScript are a way to define a contract for the shape of an object. They specify the structure of an object, including the properties and methods it should have, without providing any implementation details. Interfaces help ensure that objects conform to a specific shape, making it easier to maintain consistency across the codebase. In the video, the host uses an interface to define the shape of a 'person' object with 'first' and 'last' properties.

💡Type Annotations

Type annotations are the explicit declarations of a variable's type in TypeScript. They are used when the type cannot be inferred by TypeScript or when a developer wants to be explicit about the type for clarity and documentation purposes. Type annotations help in catching type-related errors and provide better autocompletion in IDEs. In the video, the host uses type annotations to specify the types of variables, such as defining 'hasLoggedIn' as a boolean.

💡Arrays

Arrays in TypeScript are collections of elements that are used to store multiple values in a single variable. TypeScript provides additional type safety for arrays by allowing developers to specify the type of elements within the array. This ensures that only elements of the specified type can be added to the array, preventing type mismatches. In the video, the host demonstrates how to create and work with arrays, including using the generic type syntax for arrays.

💡Tuples

Tuples in TypeScript are arrays that have a fixed size and a known type for each element. They are useful when you want to store a heterogeneous data structure where each element has a different type. Tuples allow TypeScript to enforce that the elements at specific positions in the array are of specific types. In the video, the host mentions tuples as a mechanism to handle arrays with different types of elements at different positions.

💡Objects

Objects in TypeScript are complex data structures that can store data in the form of properties, where each property is a key-value pair. TypeScript enhances the standard JavaScript objects by allowing the definition of object shapes with specific property names and types, which helps in catching errors when accessing or modifying object properties. In the video, the host creates a 'person' object and explains how TypeScript enforces the correct usage of object properties.

💡Record

The Record utility type in TypeScript is used to create an object type where the keys and values have specific types. It allows for the creation of a map-like structure where the keys are one type and the values are another. This is useful for creating indexed collections where the type of the index and the type of the value are known. In the video, the host uses the Record type to create a map of IDs to strings, allowing for type-safe key-value pairs.

💡Conditionals

Conditionals, such as if statements, are control structures in programming that execute certain code blocks based on whether a specified condition is true or false. TypeScript does not change the way conditionals are used in the code but enhances the type checking within them, ensuring type safety and preventing type mismatches. In the video, the host demonstrates how TypeScript checks the types within a string comparison within a conditional.

💡For Loops

For loops are iterative control structures in programming that repeat a block of code a specified number of times. TypeScript enhances for loops by inferring the type of the loop variable, providing better type safety and autocompletion. This helps developers avoid type-related errors and write more efficient code. In the video, the host explains how TypeScript infers the type of the loop variable in a for loop over an array of numbers.

Highlights

Introduction to the 'No BS TS' series, aimed at teaching TypeScript in 5-15 minute segments for those with a JavaScript background.

Two primary reasons to use TypeScript: to prevent common runtime errors and to code faster by having explicit types.

TypeScript helps in catching errors such as calling functions with incorrect parameters or accessing properties of null/undefined values.

A demonstration of a JavaScript bug where a boolean is incorrectly concatenated with a string, resulting in an unintended data type.

Creating a TypeScript project using `yarn init`, adding TypeScript and `ts-node` in development mode, and initializing a TypeScript configuration file.

TypeScript's ability to infer types and provide immediate feedback on type mismatches, such as the issue with 'hasLoggedIn'.

Explanation of basic TypeScript types like `string`, `boolean`, and `number`, and how to use them.

Introduction to arrays in TypeScript, including the use of generics to enforce specific types within an array.

The concept of tuples in TypeScript for working with arrays that contain a fixed number of elements of known types.

Defining objects in TypeScript and the use of interfaces to create reusable type definitions.

The utility type `record` for defining key-value pairs in TypeScript, allowing for more flexible object types.

How TypeScript works with conditionals, loops, and other control structures without changing the fundamental JavaScript syntax.

Type inference in TypeScript for loops and the `map` function, ensuring the correct type is used and providing feedback on type mismatches.

The use of string templates in TypeScript for type inference in function outputs, and how to fix type errors related to string templates.

A teaser for the next video in the series, which will cover defining types around functions in TypeScript.

The importance of TypeScript in saving time by catching errors early and speeding up the development process.

Transcripts

play00:00

welcome to no bs ts

play00:03

episode one where take a look at

play00:05

everyday types and get you started

play00:06

on your journey to understanding

play00:08

typescript now

play00:10

this whole series is about giving you

play00:13

five

play00:13

to 15 minute intros that you can take at

play00:16

your own speed

play00:17

to learn typescript particularly from a

play00:20

javascript background and the first

play00:22

thing you might want to know about

play00:23

typescript is why you'd want to use it

play00:26

well there's two big primary reasons

play00:28

that you'd want to use typescript and

play00:29

the first is it's going to save your

play00:31

bacon

play00:32

if you've had issues where you try to

play00:34

call something off of a null

play00:36

or an undefined value it's going to help

play00:38

you there if you've

play00:39

called the functions without the right

play00:41

parameters it's going to help you there

play00:43

if you don't know the fields or you put

play00:45

the wrong fields or

play00:46

type in the wrong field names into

play00:48

objects it's going to help you there

play00:49

we're going to see a lot of that stuff

play00:51

today secondarily it's going to help you

play00:55

code faster you're going to be able to

play00:57

know

play00:58

right away what the right fields are and

play01:01

know if you're missing fields

play01:02

right away so it's going to help with

play01:04

both of those things i can't wait to get

play01:06

you into it

play01:07

let's check it out right now all right

play01:10

so the first thing i'm going to do is

play01:11

create a directory called

play01:12

ts basics and then bring that up in vs

play01:16

code

play01:17

okay now let's start out with javascript

play01:19

since it's something that we're all

play01:20

familiar with

play01:21

and i'll create a file called basics.js

play01:25

and in that i'm going to go and create

play01:26

two variables the first one is a string

play01:32

and the second one is a boolean

play01:38

now i'm going to make a bug and i'm

play01:40

going to go and add to has logged in

play01:42

my last name

play01:47

and of course i want to debug that bug

play01:49

so let's do a console log and see what i

play01:52

get

play01:54

all right let's go and bring up our

play01:56

terminal

play01:59

and run node on this

play02:03

and we can see that now we've got a true

play02:05

which is what happened

play02:07

and we can see that now we have true

play02:09

space harrington so

play02:10

node has gone and coerced our boolean to

play02:13

a string

play02:14

so that we can add a string to it which

play02:15

is not really what we wanted because

play02:17

true harrington really doesn't make a

play02:18

whole lot of sense

play02:19

so can typescript help us find this bug

play02:22

and of course how do we get started with

play02:24

typescript well i'm going to go and

play02:25

create a project here

play02:27

i'm going to use yarn init for that and

play02:29

that's going to create a package.json

play02:33

and then into that package i'm going to

play02:34

add typescript

play02:38

in development mode that's going to add

play02:41

the typescript compiler

play02:44

and then i'm going to add ts node

play02:49

also in development mode and that's a

play02:51

wrapper around node that works for

play02:53

typescript files

play02:55

and then finally i'm going to go and

play02:57

initialize a typescript configuration

play02:59

file or ts config and the way to do that

play03:01

is to do mpx and then tsc which is the

play03:04

name of the typescript compiler

play03:06

and then dash dash init

play03:10

now despite being in the red this file

play03:12

is actually good

play03:14

it's got the strict typing that we want

play03:16

the reason it's going red right now is

play03:18

that it's telling us that there are no

play03:19

ts files around so there's no inputs

play03:21

so we'll fix that in a bit in the

play03:22

meantime let us

play03:24

try and use ts node on our javascript

play03:26

and see if that helps us at all

play03:32

so it's giving us exactly the same

play03:34

output as before which is great it does

play03:36

mean that we can actually

play03:38

run our javascript in ps node that's

play03:41

fine

play03:42

but it's not really helping us at all so

play03:43

let's go and change basics.js

play03:45

to basics.ts to convert it to a

play03:48

typescript file

play03:53

and already it's telling us what the

play03:55

issue is has logged in

play03:56

is an issue in fact we can see over here

play04:00

the type string is not assignable to a

play04:01

type boolean and if we want to run this

play04:03

we will get exactly

play04:06

that type of output telling us that one

play04:08

i'm not going to run it and two you've

play04:09

got a problem so scroll back up here

play04:12

and we can see that it's telling us

play04:13

exactly the same thing the type of

play04:14

string is not

play04:15

assignable to a type of boolean and now

play04:18

that problem with the ts config has gone

play04:20

away because we have a ts file we've got

play04:21

our inputs

play04:22

so how does typescript know that this is

play04:24

gonna be a problem well it's inferred

play04:26

from true that has logged in as of type

play04:29

boolean

play04:30

now how do i know that it's because i

play04:31

can do command k command

play04:33

i when i have this selected and it'll

play04:36

show me

play04:36

that it has defined has logged in as a

play04:39

boolean i know that because it's got

play04:41

that colon

play04:42

and then it's followed by boolean which

play04:43

is the type and that's exactly how you

play04:45

specify a type

play04:46

for a value in typescript is you do

play04:49

colon

play04:49

and then the type name so i'm going to

play04:51

copy and paste that into here

play04:53

and this is really neat because this

play04:54

actually kind of allows you to let vs

play04:56

code do a lot of the

play04:58

typing for you you just do command k

play04:59

command i and whatever you

play05:01

see and it'll pretty much tell you what

play05:03

the types are and give you the syntax

play05:05

which is super cool

play05:06

if i go over here i can do command k

play05:07

command i and see that this is a string

play05:09

so i can just set that to

play05:11

string i can

play05:14

fix my bug and away i go all right what

play05:17

are some other types well there is a

play05:18

number

play05:22

and that's any number there's also

play05:26

more complex types for example like a

play05:28

regex how we do a regex and typescript

play05:30

well let's go

play05:30

make one of those then when we do

play05:38

command k

play05:39

command i on that we can see that it's a

play05:41

regex and that's a built-in type

play05:46

so now that we've looked at some of the

play05:48

basic types let's talk about

play05:50

arrays so let's go and split this guy

play05:53

my username and this is an example of

play05:56

it doing that great hinting for you on

play06:00

space and now what's that going to

play06:02

output well that's a great thing i can

play06:03

do i can do

play06:04

construct names equals

play06:07

and then i can do command k command i

play06:10

and i can see

play06:11

that it's telling me that it's an array

play06:13

of names and how do i know that well

play06:15

it's got the

play06:16

open and closed brackets which is the

play06:18

same thing you'd use to de-reference

play06:19

array to basically

play06:21

tell you that this is an array so that's

play06:22

great now there's also another way to do

play06:25

arrays

play06:25

and that's to use the generic type so

play06:28

let me show you that

play06:32

specify array and then you use less than

play06:36

and greater than

play06:37

and then in between the less than and

play06:38

greater than you give the type that you

play06:40

want so let's just make an array of

play06:41

numbers

play06:44

and then in here as i'm typing if i put

play06:47

in something that's

play06:48

not a number i'm going to get a warning

play06:49

it's going to tell me that this string

play06:51

is not assignable to a type of number

play06:53

totally true

play06:55

so it's going to put in some numbers and

play06:56

now it's fine but now let's go and add

play06:58

a string on it and again i'm going to

play07:00

get that error and if you're like wait a

play07:02

second hold up hold up

play07:04

i actually have an api where i want to

play07:06

return an array that's got three numbers

play07:07

and a string can i still do that

play07:10

in typescript you definitely can there's

play07:12

a mechanism called a tuple and we'll

play07:14

cover that in this video series

play07:16

i've never seen a case where typescript

play07:18

has forbid me from making the api that i

play07:21

want to make

play07:23

right it always helps me enforce that

play07:26

and hint that to other developers but it

play07:28

never holds me back so it can do what

play07:30

you want to do

play07:31

but in this case we just want to be an

play07:33

array of numbers so there you go

play07:36

all right let's talk about objects since

play07:37

they're really important let's create a

play07:39

person object

play07:42

and we'll have a first and last name

play07:50

so how do i define that well again i'm

play07:52

going to use my command k command i

play07:54

trick

play07:55

and look at that it's going to tell me

play07:56

that what i need to do is do colon

play07:58

and then open curly braces and then

play08:00

first and last and close curly braces

play08:02

that great that's so cool so now that i

play08:05

define this object is only having a

play08:07

first and last string i've already go in

play08:09

and ask it

play08:10

to go and add in a new field say cool

play08:12

and i'll set that to true and say that

play08:14

i'm cool

play08:16

typescript will tell me no you're not

play08:17

cool because cool actually doesn't exist

play08:20

on this person which is defined as

play08:22

having just first and last on it

play08:25

but again if you're like whoa wait a

play08:26

second i want to add cool totally you

play08:28

can do that you just set it as a boolean

play08:31

or you can set it as an optional field

play08:33

you can do anything you want in

play08:35

timescript it's just going to help you

play08:37

as you define these these interfaces as

play08:39

strictly or as loosely

play08:41

as you want so let's talk a little bit

play08:45

about this type definition this seems

play08:46

like something you don't want to go and

play08:48

copy and paste all over the place

play08:49

so you want to be able to say define it

play08:51

once and then when you make changes to

play08:53

it it'll

play08:54

change everywhere so how do you define

play08:55

it once and then reuse it well you use

play08:57

the

play08:58

interface keyword and then you give the

play09:01

interface name so let's

play09:02

make it person and you just paste in

play09:06

what you want your type definition to be

play09:08

so in this case

play09:11

just reuse it like that just like person

play09:13

and again you get this great hinting so

play09:14

check this out

play09:15

my person dot and it'll tell you here

play09:18

are the fields that are available to you

play09:20

based on that interface it's just so

play09:22

great now another thing we do a lot of

play09:24

is we use

play09:24

objects as maps in javascript so let's

play09:27

see a little bit about how to do that so

play09:29

i'm going to create a

play09:31

map of ids and then say that

play09:34

10 is a let's say 20 is b

play09:37

and so how do we type that because what

play09:39

i really want to be able to do is do ids

play09:41

30 is c but what is

play09:45

already telling me that i can't do that

play09:47

because it actually inferred

play09:51

that the type here is 10 as a string 20

play09:54

is a string so when i ask for 30

play09:56

it's like no no i can't have that so how

play09:59

do i allow myself to have that

play10:01

well what i'm going to use is a utility

play10:03

type and this one is called

play10:05

record and with record i can define the

play10:08

key type

play10:09

and the value type so in this case the

play10:10

key type is a number

play10:12

and the value type is a string but they

play10:14

can be whatever you want them to be

play10:15

and so now we're fine we're good we have

play10:17

our key lookup and that's great

play10:19

so you might be asking yourself well how

play10:20

does typescript work with things like

play10:22

conditionals is that the same it

play10:24

absolutely is

play10:32

so in this case it's going to go and do

play10:33

a string comparison and it knows that's

play10:35

going to work

play10:35

because it knows that ids30 is a string

play10:38

you can actually even get checked here

play10:40

so we do 20. it's going to tell me

play10:41

that's wrong because you're comparing a

play10:43

string to a number

play10:44

so that's really nice and helpful but

play10:46

it's not going to change the way that

play10:47

you do things like conditionals

play10:49

it's only going to change when you're

play10:50

doing variable declarations

play10:52

and the only other places are things

play10:54

like loops so for example

play10:56

a for loop

play11:10

in this case the value i is inferred to

play11:13

be

play11:14

a number now you don't really need to go

play11:16

and specify that you can if you want to

play11:19

but you really should let typescript

play11:20

infer as much as possible

play11:22

so you really yeah i would leave it just

play11:24

like that because it's inferred it's

play11:25

fine

play11:26

and the other one would be things like

play11:28

4-h and map so let's try those out

play11:39

in this case again it knows that the

play11:42

input

play11:43

type is an array of numbers and so the

play11:45

parameter

play11:46

two for each is going to be of a type of

play11:49

number

play11:50

now if you were to go over a bunch of

play11:51

person records they would show up as

play11:53

persons so that's great and how does it

play11:56

work for map

play11:56

similar sort of thing

play12:04

so in this case i'm just multiplying v

play12:06

by 10

play12:07

and let's go and get the output of that

play12:11

and typescript is smart enough to infer

play12:14

that given the fact that v

play12:16

is a number and

play12:19

v times 10 is going to result in a

play12:20

number then out is going to be

play12:23

an array of numbers easy peasy lemon

play12:25

squeezy now i've already go in here and

play12:27

change this into a string template

play12:31

you see that it would change as

play12:33

inference to be

play12:35

an output of strings but if i were

play12:36

already go and

play12:40

specify this as a numeric array now it's

play12:43

giving me an error now it's telling me

play12:44

that the output of this function isn't

play12:45

mapping

play12:46

directly to what i have on the type of

play12:49

that array

play12:50

so then i can again you know fix it by

play12:52

taking out that

play12:54

string template super easy all right

play12:56

well in the next video we're going to

play12:57

take a look at how to define

play12:59

your type surround functions but of

play13:00

course in the meantime if you like the

play13:02

video hit that like button if you really

play13:03

like the video hit the subscribe button

play13:05

and click the bell button and you'll be

play13:06

notified the next time another one of

play13:08

these videos comes out

Rate This

5.0 / 5 (0 votes)

Ähnliche Tags
TypeScriptJavaScriptCoding TutorialError HandlingType InferenceDevelopment ToolsYarnVS CodeProgrammingWeb Development
Benötigen Sie eine Zusammenfassung auf Englisch?