초보 개발자의 일기
TS 문법 2 본문
void
void는 크게 3가지로 분류 가능
-리턴 값이 void
function a(): void{
}
return값이 없어야 한다.
-매개변수가 void
function a(callback: ()=>void){
}
메서드나 매개변수에서는 실제 리턴 값이 뭐든 상관하지 않는다.
그래도 void에 return값을 넣으면 안 된다.
-메서드가 void
interface A {
talk: () => void;
}
const a: A = {
talk() { return 3; }
}
메서드나 매개변수에서는 실제 리턴 값이 뭐든 상관하지 않는다.
그래도 void에 return값을 넣으면 안 된다.
declare
declare const a: string;
declare function a(x: number): number;
declare class A {}
타입만 선언하고 싶을 때는 declare를 사용하면 된다.
declare가 없으면 바로 구현부를 만드어줘야 한다.
any
어떤 타입이든 다 가능
이후 들어오는 것은 타입 검사를 포기해버린다.
그래서 any를 쓰지 마라!!!
타입 대입
타입 간 대응 가능 표
타입 가드
function numOrStr(a: number | string) {
if (typeof a === 'string') {
a.split(',');
} else {
a.toFixed(1);
}
}
numOrStr('123');
numOrStr(1);
typeof를 사용함으로써 이곳에서는 a가 확실히 string 이므로 a.split(', '); 사용 가능
else에서는 a가 확실히 number로 인식되기 때문에 사용 가능
function numOrNumArr(a: number | number[]) {
if (Array.isArray(a)) {
a.slice(1);
} else {
a.toFixed(1);
}
}
function numOrNumArr(a: number | number[]) {
if (Array.isArray(a)) {
a.slice(1);
} else {
a.toFixed(1);
}
}
numOrNumArr(123);
numOrNumArr([1,2,3]);
배열인지 아닌지는 isArray를 사용해서 구별
이렇게 타입 구분을 해서 타입 정확하게 하고 사용 가능하게 한다.
type B = { type: 'b', bbb: string };
type C = { type: 'c', ccc: string };
type D = { type: 'd', ddd: string };
type A = B | C | D;
function typeCheck(a: A) {
if (a.type === 'b') {
a.bbb;
} else if (a.type === 'c') {
a.ccc;
} else {
a.ddd;
}
}
if문을 사용해 타입 구별을 정확하게 할 수 있다.
type B = { type: 'b', bbb: string };
type C = { type: 'c', ccc: string };
type D = { type: 'd', ddd: string };
type A = B | C | D;
function typeCheck(a: A) {
if ('bbb' in a) {
a.bbb;
} else if ('ccc' in a) {
a.ccc;
} else {
a.ddd;
}
}
이렇게 in 연산자를 사용해 타입 검사를 할 수도 있다.
readonly
interface A {
readonly a: string;
b: string;
}
const aaaa: A = { a: "hello", b: "world" };
aaaa.a = "123";
읽기 전용이므로 a는 바꿀수 없다.
index sigature
type A = { a: string; b: string; c: string };
type A = { [key: string]: string };
const aaaa: A = { a: "hello" };
어떤 문자든간에 string에 값이 string이고 싶을때 사용한다.
private, protected, public
interface A {
readonly a: string;
b: string;
}
class B implements A {
private a: string = "123";
protected b: string = "world";
}
class C extends B {}
new C().a;
new C().b;
public 일반적으로 접근 가능 default 값
private은 클래스 B안에서만 사용가능
protected는 안에서는 사용 가능한데 밖에서는 사용 불가능 private와는 다르게 상속받으면 사용 가능
추상 클래스
abstract class B implements A {
private a: string = "123";
protected b: string = "world";
c: string = "wow";
abstract method(): void;
}
class C extends B {
method() {
console.log(this.a); //private이라 사용 불가
console.log(this.b); // protected고 B가 부모라서 사용 가능
console.log(this.c);
}
}
new C().a;
new C().b;
new C().c;
abstract는 반드시 상속받았을때 구현을 해야한다.
추상적으로만 만들고 구현을 다른 곳에서 한다.
그래서 interface 대신 abstract를 많이 사용한다.
optional
function abc(a: number, b?: number, c: number?) {}
abc(1)
abc(1, 2)
abc(1, 2, 3)
?는 항상 속성명 뒤에 붙여야한다.
?가 있으면 있어도 되고 없어도 된다.
function abc(...args: number[]) {}
abc(1);
abc(1, 2);
abc(1, 2, 3);
전부 다 사용하고 싶으면 이렇게 작성하면 된다.
'Frontend practice > TypeScript' 카테고리의 다른 글
TS 문법 3 (0) | 2022.09.18 |
---|---|
TS(타입 연습해보기) (0) | 2022.09.16 |
제네릭 (0) | 2022.09.16 |
TS 문법 1 (2) | 2022.08.17 |
TS 기본 (0) | 2022.08.17 |