
코딩애플 강의를 통해 배운 TypeScript를 정리한 글입니다.
2025년 2월 18일
Part 2 : 알면 도움은 되는 내용
function 함수(...a :number[]) {
console.log(a) //[1,5,2,4,1,5,3]
}
함수(1,5,2,4,1,5,3)
let [변수1, 변수1] = ['안녕', 100]
type Fish = { swim: string };
type Bird = { fly: string };
function 함수(animal: Fish | Bird) {
if ("swim" in animal) {
return animal.swim
}
return animal.fly
}
return값이 없음endpoint가 없음void쓰면됨function 함수() :never {}
class에서 쓰는 public키워드가 붙으면 모든 자식들이 이용가능class user {
public name = 'kim'
}
class에서 쓰는 private키워드가 붙으면 안에서만 이용가능class user {
private name = 'kim'
}
class에서 쓰는 protected키워드가 붙으면 extend된 class{}안에서 사용가능class User {
protected x = 10;
}
class NewUser extends User {
doThis(){
this.x = 20;
}
}
static키워드 붙으면 부모class에 직접 부여됨 (자식에게 안물려줌)class User {
x = 10;
y = 20;
}
let john = new User();
john.x //가능
User.x //불가능
class User {
static x = 10;
y = 20;
}
let john = new User();
john.x //불가능
User.x //가능
type또한 import export가능TypeScript 타입변수 숨기기 문법namespace MyNamespace {
export type NameType = number | string;
}
MyNamespace.NameType
function 함수<Type>(x: unknown[]) {
return x[0];
}
let a = 함수<number>([4, 2]);
let b = 함수<string>(['4', '2']);
function 함수<Type extends number>(x) {
return x - 1;
}
let a = 함수<number>(2);
//요소 타입지정
let 박스: JSX.Element = <div></div>;
//props 타입지정
type AppProps = {
name: string,
};
function App(props: AppProps): JSX.Element {
return <div>{message}</div>;
}
RootState, PayloadActionlet 멍멍이: [string, boolean];
멍멍이 = ["dog", true];
//rest parameter
function 함수(...x: [string, number]) {
console.log(x);
}
함수("kim", 123); //가능
함수("kim", 123, 456); //에러
함수("kim", "park"); //에러
declare let a;
//글로벌 변수
declare global {
type Dog = string
}
exportinterface CarType {
model: string;
price: number;
}
class Car implements CarType {
model: string;
price: number = 1000;
constructor(a: string) {
this.model = a;
}
}
let 붕붕이 = new Car("morning");
interface StringOnly {
[key: string]: string;
}
interface Mytype {
"font-size": Mytype | number;
}
let obj: Mytype = {
"font-size": {
"font-size": {
"font-size": 14,
},
},
};
interface Person {
age: number;
name: string;
}
type PersonKeys = keyof Person;
let a :PersonKeys = 'name'
type Car = {
color: boolean,
model : boolean,
price : boolean | number,
};
type TypeChanger <MyType> = {
[key in keyof MyType]: string;
};
type 새로운타입 = TypeChanger<Car>;
let obj :새로운타입 = {
color: 'red',
model : 'kia',
price : '300',
}
type Age<T> = T extends string ? string : unknown; //T가 string을 가지고 있는지 확인
let age : Age<string> //age는 string 타입
let age2 : Age<number> //age는 unknown 타입
type Person<T> = T extends infer R ? R : unknown;
type 새타입 = Person<string> // 새타입은 string 타입입니다