TS를 설치하는 방법에는 크게 두 가지가 있다.
npm install -g typescript
TS의 확장자명은 .ts
이다.
예제 루트에 test.ts
파일을 만들고 아래와 같이 코드를 작성해보자
function test(person: string) {
return "Hello, " + person;
}
let user = [0, 1, 2];
// 'number[]' 형식의 인수는 'string' 형식의 매개 변수에 할당될 수 없습니다.ts(2345)
document.body.textContent = test(user);
현재 인자로 string
을 받아야하는 test
함수에 number[]
형태의 값을 전달하니 VS Code가 오류를 보여주고 있는 상황이다.
혹시 이 상태로 컴파일하면 컴파일 될까?
컴파일 명령어는 아래와 같다.
tsc test.ts
해당 명령어를 실행하면 컴파일은 된다.
function greeter(person) {
return 'Hello, ' + person;
}
var user = [0, 1, 2];
document.body.textContent = greeter(user);
위와 같은 결과로 알 수 있는 점은 TS는 코드에 오류가 존재하더라도 JS로 컴파일이 가능하다.
하지만 TS는 코드가 예상대로 작동하지 않을 것이라는 경고를 띄워준다.
interface Person {
firstName: string;
lastName: string;
}
function test(person: Person) {
return 'Hello, ' + person.firstName + ' ' + person.lastName;
}
let user = { firstName: 'Son', lastName: 'Wonjae' };
document.body.textContent = test(user);
interface
로 타입을 정의하면 별도의 실행구문 없이 interface
가 요구하는 형태를 사용하는 것만으로도 interface
를 구현할 수 있다.