TypeScript -9-

mh·2022년 5월 4일
0

TypeScript

목록 보기
9/17
post-thumbnail

Photo by Krystian Tambur on Unsplash

클래스를 이용해 사전 (hashmap) 만들기

해쉬 알고리즘을 사용한 해쉬 맵 만들기

넣어줄 데이터의 예시

{
    "potato": "Food",
    "rice": "Also food"
}

컨스트럭터에서 직접 초기화 하지 않는 프로퍼티 words 를 생성

class Dictionary {
    private words
}

이런 형태와 다름

class Dcit {
  constructor (
          private x:string,
          protected y:string
      ) {}
}

프로퍼티의 key와 value 타입 지정하기

Words라는 새 타입을 생성해주고 words의 타입으로 줌


type Words = {
    [key:string]: string
}

class Dictionary {
    private words: Words
}

여기서 Words 타입은 string만을 property로 가지는 객체

type Words = {
    [아무거나:string]: string
}

[아무거나:string] -> key가 string 이어야 한다는 뜻
[아무거나:string]: string value도 string이여야 한다는 뜻
프로퍼티의 이름은 모르지만 프로퍼티의 타입은 알때 사용

constructor 바깥의 값 수동으로 초기화시키기

words는 컨스트럭터에 포함시켜주지 않았기 때문에 이런 에러가 발생한다.

컨스트럭터 바깥에서 words를 선언하고 싶다면, 바깥에서 선언한 뒤
컨스트럭터를 작성해서 words를 수동으로 초기화시켜준다.

class Dictionary {
    private words: Words
    constructor() {
        this.words = {}
    }
}

Word 클래스 만들고 단어 만들기

public 키워드로 문자열을 가지는 term과 def프로퍼티를 만들어준다.

class Word {
    constructor (
        public term:string,
        public def :string,
    ) {}
}

const khajiit = new Word("Khajiit", "a word for 'carpet'");

단어 khajiit을 Word생성자로 추가해주고 컨스트럭터에서 요구하는 값들을 넘겨준다.

단어를 추가해주는 메소드 생성

class Dictionary {
    private words: Words
    constructor() {
        this.words = {}
    }
    add(word:Word) {
		
    }
}

add() 안에 조건문을 작성

type Words = {
    [key:string]: string
}

class Dictionary {
    private words: Words
    constructor() {
        this.words = {}
    }
    add(word:Word) {
        if(this.words[word.term] === undefined) {
        	this.words[word.term] = word.def;
        }
    }
}

class Word {
    constructor (
        public term:string,
        public def :string,
    ) {}
}

const khajiit = new Word("Khajiit", "a word for 'carpet'");

if(this.words[word.term] === undefined) 주어진 단어가 사전에 존재하지 않을때

this.words[word.term] = word.def; 이 단어를 사전에 새로 추가하겠다.

사전에 단어를 추가하기

만들어진 add()메소드에 khajiit이라는 words오브젝트를 넣으면 사전에 단어가 추가된다.

const dict = new Dictionary()

dict.add(khajiit)

단어뜻을 불러오는 기능 만들기

term(단어)를 이용해서 단어 뜻을 불러오기
def()메소드 작성

class Dictionary {
    private words: Words
    constructor() {
        this.words = {}
    }
    add(word:Word) {
        if(this.words[word.term] === undefined)
        this.words[word.term] = word.def; 
    }
    def(term:string){
        return this.words[term]
    }
}

def는 term을 받고 wrods안의 term키에 해당되는 value를 반환할것임
그러면 단어에 맞는 뜻이 반환됨

컴파일 된 JS코드 작동시켜보기

정리

  • 오브젝트의 프로퍼티 타입 지정하는 방법 (타입을 만드는 방법)
type Words = {
    [key:string]: string
}
  • 프로퍼티를 constructor 바깥에서 선언하고 수동으로 초기화하기 (내가 원하는 프로퍼티 만들고 원하는대로 초기화하기)
class Dictionary {
    private words: Words
    constructor() {
        this.words = {}
    }
}
  • class를 타입처럼 사용하기
class Dictionary {
    private words: Words
    constructor() {
        this.words = {}
    }
  // 밑에서 만든 Word 클래스가 add파라미터 word의 타입으로 지정됨
  // 이 파라미터가 Word 클래스의 인스턴스이기를 바라면 이렇게 사용가능
    add(word:Word) {
        if(this.words[word.term] === undefined) {
        	this.words[word.term] = word.def;
        }
    }
}

class Word {
    constructor (
        public term:string,
        public def :string,
    ) {}
}
  • concrete type, generic 에 이어 class를 타입으로 사용가능

  • argument로 전달할 수 있는 다른 타입 -> interface

profile
🤪🤪🤪🤪🤪

0개의 댓글