본문 바로가기
반응형

전체 글52

[TypeScript] object index signature (인덱스 서명) * 본 포스팅은 필자가 개인적으로 학습한 내용정리 및 리뷰를 위해 포스팅합니다. interface UserType { name : string, age : string, address : string } let user :UserType = { name : 'hoo', age : '27', address : 'seoul' } ▲ object에 타입을 일일이 타입을 지정해줘야 하는 불편함이 있다. interface UserType { [key : string] : string, } let user :UserType = { name : 'hoo', age : '27', address : 'seoul' } ▲ index signature 를 쓰면 { [Key: T]: U } 형식으로 객체가 Key를 여러 개 .. 2023. 11. 1.
[TypeScript] implements 키워드 * 본 포스팅은 필자가 개인적으로 학습한 내용정리 및 리뷰를 위해 포스팅합니다. 앞에서 배운 interface는 object 타입지정할 외 하나의 용도가 있는데 바로 class의 타입을 확인하고자 할 때interface와 implements를 활용한다. class User { name : string; age : number = 27; constructor(a :string) { this.name = a } } let user = new User('hoo'); ▲ class User로 부터 생성되는 object들은 name과 age의 속성을 가지게 된다. class가 name, age 속성을 가지고 있는지 타입으로 확인하려면 interface + implements 키워드로 확인한다!! interface.. 2023. 10. 31.
[TypeScript] Generic 함수 만들기 * 본 포스팅은 필자가 개인적으로 학습한 내용정리 및 리뷰를 위해 포스팅합니다. function 함수(x :unknown[]) { return x[0] } let result = 함수([4,2]) console.log(result + 1) //'a' is of type 'unknown' ▲ result의 타입은 unknown이기 때문에 앞에서 배운 narrowing 또는 as를 사용해야 하는 불편함이 있다. 이를 해결하기 위해!! function 함수(x :Type[]) :Type { return x[0] } let result = 함수([4,2]) console.log(result) ▲ 파라미터로 타입을 입력하는 Generic 함수를 사용한다!! function 함수(x : Type){ return x.. 2023. 10. 25.
[TypeScript] class / object 타입 지정 * 본 포스팅은 필자가 개인적으로 학습한 내용정리 및 리뷰를 위해 포스팅합니다. class를 만들 때 타입지정하는 방법을 알아보자! class User { name :string; constructor(){ this.name = 'HOO' } } let user1 = new User(); let user2 = new User(); ▲ constructor()는 this.name을 사용하기 위해서는 필드값에 name이 미리 있어야 한다. class User { name :string; constructor(a :string){ this.name = a; } } let user1 = new User('kim'); let user2 = new User('hoo'); console.log(user2) // na.. 2023. 10. 19.
[TypeScript] 색다르게 타입도 변수에 담아서 쓰자(type alias) * 본 포스팅은 필자가 개인적으로 학습한 내용정리 및 리뷰를 위해 포스팅합니다. type Userid = string | number | undefined; let 아이디 :Userid = abcd; ▲ type alias를 만들어서 변수에 타입을 담아서 이용한다. type Username = { readonly name : string } const 사용자명 :Username = { name : 'KIM' } ▲ readonly를 사용하면 추후 object 자료 수정을 막을 수 있다!! type Id = string; type Pwd = number; type Email = Id | Pwd; ▲ union type으로 타입을 합치기도 가능하다. type Mathscore = { x : number };.. 2023. 10. 18.
[TypeScript] 함수에 타입 지정하는 법 * 본 포스팅은 필자가 개인적으로 학습한 내용정리 및 리뷰를 위해 포스팅합니다.function 함수(x :number) :number { return x + 1 } 함수('2') X▲ 함수는 파라미터, return 값을 타입지정 할 수 있다.(number로 지정했기에 문자를 넣으면 오류!! function 함수(x :number) :void { 1 + 2 }▲ 함수에서 void 타입 활용 가능(return을 사전에 막을 수 있음) function 함수(x :number) :void { } ---------------------------------- function 함수(x? :number) :void { }▲ 타입지정된 파라미터는 필수!!! 하지만 아래와 같이 변수? :number는 변수 :number.. 2023. 10. 17.
반응형