Photo by Krystian Tambur on Unsplash
해쉬 알고리즘을 사용한 해쉬 맵 만들기
넣어줄 데이터의 예시
{
"potato": "Food",
"rice": "Also food"
}
컨스트럭터에서 직접 초기화 하지 않는 프로퍼티 words 를 생성
class Dictionary {
private words
}
이런 형태와 다름
class Dcit {
constructor (
private x:string,
protected y:string
) {}
}
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이여야 한다는 뜻
프로퍼티의 이름은 모르지만 프로퍼티의 타입은 알때 사용
words는 컨스트럭터에 포함시켜주지 않았기 때문에 이런 에러가 발생한다.
컨스트럭터 바깥에서 words를 선언하고 싶다면, 바깥에서 선언한 뒤
컨스트럭터를 작성해서 words를 수동으로 초기화시켜준다.
class Dictionary {
private words: Words
constructor() {
this.words = {}
}
}
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를 반환할것임
그러면 단어에 맞는 뜻이 반환됨
type Words = {
[key:string]: string
}
class Dictionary {
private words: Words
constructor() {
this.words = {}
}
}
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