코딩/TypeScript

TypeScript 003. TypeScript 작성

꼬낄라 2022. 3. 16. 20:34

TypeScript에서 제공하는 몇 가지 새로운 도구들을 사용해보자. 여기 표시된 대로 함수 인수인 ‘person’에 : string 타입 표기를 추가해보자.

function greeter(person: string) {

return "Hello, " + person;

}

let user = "Jane User";

document.body.textContent = greeter(user);

연습 해보기

타입 표기

TypeScript의 타입 표기는 함수나 변수의 의도된 계약을 기록하는 간단한 방법이다. 이 경우, greeter 함수를 단일 문자열 매개변수로 호출하도록 한다. 대신 배열을 전달하여 greeter 함수를 호출하도록 변경해보자.

function greeter(person: string) {

return "Hello, " + person;

}

let user = \[0, 1, 2\];

document.body.textContent = greeter(user);
Argument of type 'number\[\]' is not assignable to parameter of type 'string'.Argument of type 'number\[\]' is not assignable to parameter of type 'string'.

연습 해보기

다시 컴파일해보면, 오류가 발생한 것을 볼 수 있다:

error TS2345: Argument of type 'number\[\]' is not assignable to parameter of type 'string'.

마찬가지로, greeter 호출에 대한 모든 인수를 제거해보자. TypeScript는 예상치 못한 수의 매개변수를 사용하여 이 함수를 호출했음을 알려준다. 두 경우 모두, TypeScript는 코드 구조와 사용자가 제공한 타입 표기를 기반으로 정적 분석을 제공할 수 있다.

오류가 있었음에도, greeter.js 파일은 여전히 생성된다. 그러나 이 경우, TypeScript는 코드가 예상대로 실행되지 않을 것이다.

인터페이스

샘플을 좀 더 발전시켜보자. 여기 firstName과 lastName 필드가 있는 객체를 설명하는 인터페이스가 있다. TypeScript에서는, 내부 구조가 호환되는 경우 두 개의 타입이 호환된다. 이를 통해, 명시적인 implements 절 없이도 인터페이스가 필요로 하는 모양을 갖추는 것만으로 인터페이스를 구현할 수 있다.

interface Person {

firstName: string;

lastName: string;

}

function greeter(person: Person) {

return "Hello, " + person.firstName + " " + person.lastName;

}

let user = { firstName: "Jane", lastName: "User" };

document.body.textContent = greeter(user);

연습 해보기

클래스

마지막으로, 클래스를 사용하여 예제를 확장해보자. TypeScript는 클래스 기반 객체 지향 프로그래밍 지원과 같은 JavaScript의 새로운 기능을 지원한다.

몇 가지 퍼블릭 필드와 생성자를 포함한 Student 클래스를 생성해보자.

또한, 생성자에 대한 인수에 public을 사용하는 것은 자동으로 그 이름을 가진 속성을 만들 수 있게 해주는 약어이다.

class Student {

fullName: string;

constructor(

public firstName: string,

public middleInitial: string,

public lastName: string

) {

this.fullName = firstName + " " + middleInitial + " " + lastName;

}

}

interface Person {

firstName: string;

lastName: string;

}

function greeter(person: Person) {

return "Hello, " + person.firstName + " " + person.lastName;

}

let user = new Student("Jane", "M.", "User");

document.body.textContent = greeter(user);

연습 해보기

TypeScript 웹 앱 실행해보기

greeter.html에 다음과 같이 입력:

<!DOCTYPE html\>

<html>

<head>

<title>TypeScript Greeter</title>

</head>

<body>

<script src\="greeter.js"\></script>

</body>

</html>

브라우저에서 greeter.html을 열어 첫 번째 간단한 TypeScript 웹 애플리케이션을 실행 해보자!