// named function
function add(x: number, y: number): number {
return x + y;
}
// arrow function
let add = (x: number, y: number): number => {
return x + y;
}
TypeScript에서 함수를 표현할 때는 매개변수의 타입과 리턴 값의 타입을 명시해야 한다.
let add = (x: number, y: number): void => {
console.log(x+y);
}
함수의 리턴 값이 없다면 리턴 값의 타입(매개변수 뒤)에 : void를 표기한다.
let user = (name: string, age: number): string => {
return `이름: ${name}, 나이: ${age}`;
}
user('kim'); // Expected 2 arguments, but got 1.
user('kim', 20); // 이름: kim, 나이: 20
user('kim', 20, 30); // Expected 2 arguments, but got 1.
TypeScript에서는 함수 호출 시 매개변수 개수에 맞춰 전달인자를 전달 해야한다.
let user = (name: string, age?: number): string => {
return `이름: ${name}, 나이: ${age}`;
}
user('kim'); // 이름: kim, 나이: undefined
user('kim', 20); // 이름: kim, 나이: 20
user('kim', 20, 30); // Expected 1-2 arguments, but got 3.
특정 변수가 있어도 되고 없어도 되는 경우 매개변수 뒤에 optional 기호(?)를 표기한다. 전달인자를 하나만 전달하면 undefined를 반환한다.
주의점 - 선택적 매개변수 뒤에있는 매개변수는 모두 선택적 매개변수여야하기 때문에 반드시 필수 매개변수 뒤에 위치한다.
let user = (name: string, age = 20): string => {
return `이름: ${name}, 나이: ${age}`;
}
user('kim'); // 이름: kim, 나이: 20
user('kim', undefined); // 이름: kim, 나이: 20
user('kim', 50); // 이름: kim, 나이: 50
user('kim', 20, 30); // Expected 1-2 arguments, but got 3.
JavaScript의 default parameter와 동일하게 동작하며 옵셔널 기호(?)와 타입은 생략(타입 추론)한다.
함수 호출 시 전달인자가 없거나 undefined를 전달할 경우 매개변수의 값을 미리 할당할 수 있다.
undefined를 전달할 경우 기본 매개변수 값을 반환한다.
기본 매개변수와 전달인자 모두 값이 있는 경우 전달인자 값을 반환한다.
class Person {
// 프로퍼티를 따로 추가하지 않고 생성자 메서드에서 this 키워드를 통해 생성
constructor(name, age) {
this.name = name;
this.age = age;
}
info() {
console.log(`이름: ${this.name}, 나이: ${this.age}`);
}
}
const user = new Person('kim', 20);
user.info(); // 이름: kim, 나이: 20
Person 클래스를 사용하여 name, age 속성과 info() 메서드를 정의하고 user 인스턴스를 생성하였다.
class Person {
// 프로퍼티 선언 및 타입 정의
name: string;
age: number;
// 생성자 매개변수 타입 정의
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
// 메서드 리턴 타입 정의
info(): void {
console.log(`이름: ${this.name}, 나이: ${this.age}`);
}
}
const user = new Person('kim', 20);
user.info(); // 이름: kim, 나이: 20
JavaScript의 클래스 문법과 거의 비슷하지만 TypeScript에서는 프로퍼티 타입, 생성자 매개변수 타입, 메서드 리턴 타입을 정의하였다.
// 부모 클래스, 수퍼 클래스
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
// 자식 클래스, 서브 클래스
class Development extends Person {
job: string;
constructor(name: string, age: number, job: string) {
super(name, age);
this.job = job;
}
introduce(): void {
console.log(`이름: ${this.name}, 나이: ${this.age}, 직업: ${this.job}`);
}
}
const user = new Development('lee', 20, 'developer');
user.introduce(); // 이름: lee, 나이: 20, 직업: developer
인터페이스와 마찬가지로 Development 클래스는 기존에 정의한 Person 클래스를 extends 키워드를 통해 상속받아 새로운 클래스를 만들 수 있으며 부모 클래스의 모든 프로퍼티와 메서드를 사용할 수 있다.
주의점 - 부모 클래스는 여러개의 자식 클래스를 가질 수 있지만 자식 클래스는 하나의 부모 클래스만 상속받을 수 있다.
또한 부모 클래스는 자식 클래스의 프로퍼티와 속성을 사용할 수 없다.
class Person {
name: string; // public 키워드를 선언한 것과 동일
public age: number;
private job: string;
protected gender: string;
constructor(name: string, age: number, job: string, gender: string) {
this.name = name;
this.age = age;
this.job = job;
this.gender = gender;
}
introduce(): void {
console.log(`이름: ${this.name}, 나이: ${this.age}, 직업: ${this.job}, 성별: ${this.gender}`);
}
}
let user = new Person('park', 30, 'nothing', 'male');
user.name; // park
user.age; // 30
user.job; // Property 'job' is private and only accessible within class 'Person'
user.gender; // Property 'gender' is protected and only accessible within class 'Person' and its subclasses
public - 어디에서나 접근 가능, TypeScript에서는 기본값이며 생략 가능
private - 클래스 내부(this)에서만 접근 가능, 클래스 외부에서 접근 불가
protected - 클래스 내부(this)와 상속받은 자식 클래스(this)에서만 접근 가능
class Person {
// 접근제어자 키워드를 먼저 선언
public readonly age: number;
constructor(age: number) {
this.age = age;
}
// 메서드에는 readonly 사용 불가
readonly introduce(): void { // 'readonly' modifier can only appear on a property declaration or index signature.
console.log(`나이: ${this.age}`);
}
}
let user = new Person(20);
user.age = 30; // Cannot assign to 'age' because it is a read-only property.
readonly 키워드를 사용하면 해당 프로퍼티는 읽기 전용이 되며 메서드에는 사용할 수 없다.
접근 제어자와 같이 사용할 경우 접근 제어자 키워드를 먼저 선언한다.
class Test {
static a: number = 5; // 직접 초기화
static b: number;
constructor() {
Test.b = 10;
}
}
console.log(Test.a); // 5
console.log(Test.b); // undefined
let instance = new Test();
console.log(Test.b); // 10
console.log(instance.b); // Property 'b' does not exist on type 'Test'. Did you mean to access the static member 'Test.b' instead?
정적(static) 속성은 인스턴스를 생성하지 않아도 클래스의 프로퍼티나 메서드에 접근할 수 있다. 인스턴스를 통해 프로퍼티에 접근할 수 없다.
프로퍼티 선언 시 직접 초기화하거나 생성자 메서드에서 초기화한다.