타입스크립트(애플코딩)3
HTML 변경과 조작할때 주의
<h4 id='title'> 안녕하세요 </h4>
let 제목 = document.querySelector('#title');
제목.innerHTML = '반가워요'
// 에러발생 : 제목은 Element | null 이기때문에 에러가 발생한다.
이런경우 narrowing을 사용해야한다.
// 1번
if(제목 !== null){
제목.innerHTML = '반가워요'
}
// 2번
if(제목 instanceof Element){
제목.innerHTML = '반가워요'
}
// 3번
let 제목 = document.querySelector('#title') as Element;
제목.innerHTML = '반가워요'
// 4번
if(제목?.innerHTML != undefined){
제목.innerHTML = '반가워요'
}
위 방법중에는 2번 방법이 제일 좋은 방법이다!
class 타입지정
class Person {
constructor(){
this.name = 'kim'
}
}
let 사람1 = new Person();
let 사람2 = new Person();
이런식으로 클래스를 만들어줄 수 있다.
class Person {
data = 0;
}
let 사람1 = new Person();
let 사람2 = new Person();
console.log(사람1.data) // 0;
class Person {
// 변수를 미리 선언해야지 아래에서 this.name을 사용할 수 있다.
name:string;
constructor(a :string){
this.name = a
}
// 이자리는 prototype 함수를 만들 수 있다.
함수(a : string){
console.log('안녕' + a)
}
}
let 사람1 = new Person('uri');
let 사람2 = new Person('ura');
console.log(사람1) // name: 'uri'
여기에선 return값은 타입지정을 해주지 않아도 된다.
interface
interface Square = {color : string, width:number}
let 네모 = { color:'red', width:100 }
type보다 interface의 장점
extends로 복사가 가능하다
interface Stydent {
name : string
}
interface Teacher {
name : string,
age : number
}
let 학생 : Student = { name : 'kim' }
let 학생 : Teacher = { name : 'kim', age : 20 }
이렇게 되어있는걸 extends로 중복된걸 복사가 가능하다.
interface Stydent {
name : string
}
interface Teacher extends Stydent {
age : number
}
let 학생 : Student = { name : 'kim' }
let 학생 : Teacher = { name : 'kim', age : 20 }
또한 중복 선언이 가능하다.
interface Stydent {
name : string
}
interface Stydent {
score : string
}
interface는 유연하고 type은 엄격하다.
...rest parameter
여러개의 파라미터가 들어올 수 있다.
function 함수(...a :number[]){
console.log(a)
}
함수 (1,4,5,3,2)
// [1,4,5,3,2]
destructuring
let [변수1, 변수2] = ['안녕', 100]
console.log(변수1) // 안녕
let { student : student, age : age } = { student : true, age: 20}
// student, age 는 키 값이 같기 떄문에 하나만 적어줘도 된다.
let { student , age } = { student : true, age: 20}
in 키워드
type Fish = {swim : string}
type Bird = {fly : string}
function 함수 (animal : Fish | Bird){
//Fish타입인지 검사가능하다.
if('swim' in animal){
animal.swim
}
}
instanceof
오브젝트 instanceof 부모class
오브젝트의 부모를 찾는 키워드
type Car = {
wheel : '4개'
color :string
}
type Bike = {
wheel : '2개'
color :string
}
function 함수( x :Car | Bike){
if(x가 Car타입이냐){
}
}
여기서 narrowing하는 방법
속성명 in 오브젝트 자료(불가능 : 단독으로만 사용하는 속성이 있지않고 공통적인것만 있음)
오브젝트 instanceof 부모 class(불가능 : 부모class가 없다.)
강제로 리터럴 속성을 넣어놓는다.
function 함수 (x: Car |Bike){
if(x.wheel === '4개'){
console.log('x는 Car타입이에요')
}
}
generic
function 함수(x : unknown[]) {
return x[0]
}
let a = 함수 ([4,2])
console.log(a)
이건 return값이 number일 것 같지만 x를 unknown이라고 타입을 지정해놨기 때문에 retrun도 unknown이 나올 수 밖에 없다.
그래서 console.log(a+1)을 하면 a의 타입은 unknown이기 때문에 에러가 발생한다.
function 함수<T>(x : T[]):T {
return x[0]
}
let a = 함수<number>([4,2])
console.log(a)
이렇게 되면 함수를 실행할때 타입을 동적으로 줄 수 있다.
function 함수<T>(x : T){
retrun x - 1
}
let a = 함수<number>(100)
// 에러발생 : x가 number타입이 아니다.
a변수를 선언전에 x가 머가 들어올지 모르는 상황이기 때문에 당연히 에러가 발생할 수 있다.
해결하기위해선 narrowing해주거나 타입파라미터를 제한주면 된다.
function 함수<T extends number>>(x : T){
retrun x - 1
}
let a = 함수<number>(100)
number타입이 맞는지 체크하고싶을때 사용할 수 있다.
T가 number를 만족하는지? 체크한다.