typescript HTML요소 type지정, Class 사용

김명성·2022년 3월 18일
0

typescript

목록 보기
3/8
// Assertion 사용
const title = document.querySelector('#title') as Element;

// Narrowing 
if(title !== null){
title.innerHTML = 'some txt';
}
// Narrowing
if(title instanceof Element){
    title.innerHTML = 'some txt';
}

//optional chaining
if(title?.innerHTML){
    title.innerHTML = 'some txt'
}

// 타입스크립트의 정확한 type Narrowing
//Element type에서 파생된 HTMLAnchorElement,HTMLHeadingElement,HTMLButtonElement ...
// 사용하려는 tag에 맞는 파생된 type을 찾아 입력해야 한다.

//Anchor
let link = document.querySelector('.link');
if(link instanceof HTMLAnchorElement){
link.href = 'http://kakao.com';
}

//Button
let btn = document.querySelector('#button')
if(btn instanceof HTMLButtonElement){
btn.addEventListener('click',function(){
    console.log('hello world');
})
}
//Image
const img = document.querySelector('#image')
if(img instanceof HTMLImageElement){
img.src = 'new.jpg'
}

//복수의 HTML요소 type Narrowing
const naverLink = document.querySelectorAll('.naver')

//방법 1.
naverLink.forEach(
    (link) => {
    if(link instanceof HTMLAnchorElement){
    link.href = 'https://kakao.com'
}
})
//방법 2.
for(let i = 0; i < 3; i++){
    let a = naverLink[i];
    if(a instanceof HTMLAnchorElement){
    a.href = 'https://kakao.com'
	}
}

class 문법을 사용할 때 type 지정

1.
class Anchester {
    //class 필드 값을 입력하는 장소
    //typescript는 필드값에 인스턴스가 가질 프로퍼티의 type을 지정해주어야 한다.
    name:string;
    constructor(name:string){
        this.name = name;
    }
  // prototype method. 상속으로 인스턴스가 사용이 가능하지만 직접 갖지 않는 메서드
    myFunc(a:string){
        console.log('안녕'+a);
    }
}

const person = new Anchester('Myung-seong');

2.
class Car {
    model:string;
    price:number;
    constructor(carModel:string,carPrice:number){
        this.model = carModel,
        this.price = carPrice
    }
    tax():number{
        return this.price / 10
    }
}

const sonata = new Car('Sonata',26000000)
console.log(sonata); 

console.log(sonata.tax()); // 2600000


3.
// 문자,숫자로 들어오는 인수를 인스턴스의 배열 프로퍼티에 나누어 담기
class seperateWord {
    stringArray: string[]
    numberArray: number[]
    constructor(...wordChunk:(number|string)[]){
        this.stringArray = [];
        this.numberArray = [];
        [...wordChunk].forEach((word)=>{
            if(typeof word === 'string'){
                this.stringArray.push(word)
            }else if(typeof word === 'number'){
                this.numberArray.push(word)
            }
        })   
    }
}
const chunks = new seperateWord('132','하하하',2400,'안녕',130,777)
chunks.stringArray //(3) ['132', '하하하', '안녕']
chunks.numberArray //(3) [2400, 130, 777]

0개의 댓글