class Person {
first: string;
last: string;
constructor(first: string, last: string) {
this.first = first;
this.last = last;
}
getName() {
return this.first + ' ' + this.last;
}
}
const marie = new Person('Marie', 'Curie');
const personName = marie.getName();
declare let array: number[];
for (const el of array) {
// ...
}
인덱스가 필요한 경우 forEach 사용하기
declare let array: number[];
array.forEach((el, i) => {
// ...
});
class Foo {
method() {
console.log(this);
[1, 2].forEach(function(i) {
console.log(this);
});
}
}
const f = new Foo();
f.method();
// Prints Foo, undefined, undefined in strict mode
// Prints Foo, window, window (!) in non-strict mode
위의 예시보다는 아래의 예시처럼 사용하기
class Foo {
method() {
console.log(this);
[1, 2].forEach(i => {
console.log(this);
});
}
}
const f = new Foo();
f.method();
// Always prints Foo, Foo, Foo
단축 객체 표현 예시)
declare let obj: {props: {a: string; b: number; }; };
const {props} = obj;
const {a, b} = props;
구조 분해 할당 예시)
declare let obj: {props: {a: string; b: number; }; };
const points = [
[1, 2, 3],
[4, 5, 6],
];
points.forEach(([x, y, z]) => console.log(x + y + z));
// Logs 6, 15
function parseNum(str, base=10) {
return parseInt(str, base);
}
async function getJSON(url: string) {
const response = await fetch(url);
return response.json();
}
<이펙티브 타입스크립트> (댄 밴더캅 지음, 장원호 옮김, 인사이트, 2021)