TypeScript

김지영·2022년 5월 29일
1

TypeScript is a (typed) superset of JavaScript. The main difference between TS and JS is that the former sets the types for the variables. Doing so helps clarifying the intentions of the developer's usage of each variable/function/etc., and it can also reduce the amount of the errors that JavaScript could have caused. A downside is that TypeScript compiles to plain JavaScript, which negatively affects its runtime.

In JS, we could freely re-assign a value to an existing variable with a different type than its previous one. For example, our code editor won't complain if we did the below:

let one = "one";	// line 1
console.log(one);	// will print "one"
one = 1;			// line 3
console.log(one);	// will print 1

However, if we did the same thing in TS, we will get an error on line 3 because the variable "one" is a string type yet you're trying to assign a new value to it with a different type (i.e. number type). But the piece of code has one more problem, and it's on line 1. In TypeScript, when you declare a variable, you need to specify its type at the time of declaration. So line 1 (in TS) should really be:

let one: string = "one";

For the case of arrays, you will put the type of the array's elements in angle brackets like this: Array<number>. You can have more than one type of elements in an array by doing this:

let arr: (number | string)[] = ["one", 2, 3, 4];

For an object type, we use an interface. The following is copied from my class note (credit goes to Code Camp):

// Object Type
interface IProfile {
    school: string
    age: number
}

let profile: IProfile = {
    school: 'Squirrel Elementary School',
    age: 13
}

profile.age = "bbb"
profile
아줌마

0개의 댓글