Type 설정하기

이동규·2023년 10월 23일

Typescript

목록 보기
5/6

타입을 지정하는 방법

type Mytype = 3;// 타입에 값을 할당해서 특정 값만 타입을 지정  할 수 있다.
type Mynum = number;// 타입값에 타입을 할당 할 수 있다.
type func = ()=>void; 
let num:Mytype = 3;
let myNum:Mynum = 10;
const hello:func = () =>{
	console.log('안녕하세요');
	}

제네릭을 사용하여 타입을 변수에 저장하는 예

type Container<T> = {value:T};
const obj:Container<number> = {value:26};
const testObj:container<string> = {value:"leedongkyu"};

즉, 타입에 타입을 할당하는 것은 그 타입만 사용 할 수 있다는 의미이다.

타입스크립트 key of

keyof를 사용하면 객체의 속성이름을 타입으로 사용 할 수 있다.

type Person = {
    name:string;
    age:number;
    address:string
}
type PersonKey  = keyof Person;// name , age , address를 문자열로 추출한다.
const myPerson:Person = {
    name:"lee",
    age:26,
    address:"suwon"
}
const key:PersonKey = "age";
const StudentAge = myPerson[key];//동일
myPerson["age"];//동일

class를 제네릭 형태로 구성하기

class Test<T>{
    private value:T;
    constructor(para:T){
        this.value = para;
    }
    read = ():void=>{
        console.log(this.value);
        
    }
}

const grade = new Test<number>(3);
grade.read();

0개의 댓글