카테고리 없음

타입스크립트(ZeroCho) 기본문법 3

stella0905 2023. 8. 10. 13:47

{}와 object

// {}, Object 모든 타입(null과 undefined 제외)
const x: {} = 'hello';
const y: Object = 'hi'
// 실제 객체
const xx: object = 'hi';
const yy: object = {hello : 'world'}; 
// 실제 사용할땐 object지양, interface, type, class 사용
const z: unknown = 'hi'

//unknown = {} | null | undefined
if(z){
  z;
}

{}, Object는 객체가 아닌 모든 타입을 가리킨다. 객체는 소문자로 object인데 실제 사용할 땐 object는 지양하고 

interface, type, class를 사용하는게 좋다.

 

unknown = {} | null | undefined 공식이 4.8버전에서 성립하게 되었다.

 

readonly, 인덱스드 시그니처, 맵드 타입스

readonly

interface A {
  readonly a: string;
  b: string;
}

const aaaa: A = {a:'hello', b:'world'};
aaaa.a = '123' //읽기 전용 속성이므로 'a'에 할당할 수 없습니다.

readonly는 읽기전용이기 때문에 수정하거나 할당하려고하면 에러가 발생한다.

 

인덱스드 시그니처

type A = {a : string, b: string, c: string};
const aaaa: A = {a:'hello',b:'world',c:'uri'}

키, 값의 타입을 다 string으로 정의하고 싶다면

type A = {[key:string]:string};
const aaaa: A = {a:'hello',b:'world',c:'uri'}

이렇게 한번에 사용할 수 있다.

 

 

맵드 타입스

type B = 'Human'|'Mammal'|'Animal'
type A = {[key in B]:string};
const aaaa: A = {Human:'hello',Mammal:'world',Animal:'uri'}
// key가 B에 해당되면서 값이 스트링인 타입으로 정의

 

클래스의 새로운 기능들

class A {
  a: string;
  b: number;
  constructor(a:string, b:number = 123){
    this.a = a;
    this.b = b;
  }
  method(){

  }
}

type AA = A;
const a: A = new A('123');
const b: typeof A = A;

클래스 자체의 타입은 typeof A 이고 클래스 이름은 인스턴스를 가르킨다.

 

옵셔널, 제네릭 기본

옵셔널(?)

속성명뒤에 ? 로 표시하고 있어도 되고 없어도 된다는 의미

function abc(a: number, b?: number, c: number?) {}
abc(1)
abc(1, 2)
abc(1, 2, 3)

let obj: { a: string, b?: string }  = { a: 'hello', b: 'world' }
obj = { a: 'hello' };

 

제네릭

function add(x: string, y:string):string{return x + y }
function add(x: number, y:number):number{return x + y }

add(1,2);
add('1','2')

위코드는 함수명이 중복이기 때문에 에러가 발생한다.

function add(x: string | number, y:string | number):string | number{return x + y }

add(1,2);
add('1','2')

이렇게 변경을 해줘도 에러가 발생한다.

이걸 해결하고자 제네릭이 나왔다.

함수에는 함수명 뒤에 <T>로 수정해주고 타입을 다 T로 수정해준다.

function add<T>(x:T, y:T):T{
  return x + y
}

add(1,2);
add('1','2')
function add<T extends string>(x:T, y:T):T{
  return x + y
}

extends를 사용해서 제한을 걸 수 있다.  제한이 없는경우에는 (...args : any)를 사용해도 된다. 

 

기본값 타이핑

const a = (b:number = 3, c:number = 5)=>{
  return '3'
}

⬇️

// 기본값
const a = (b = 3, c = 5)=>{
  return '3'
}
const a = (b:{children:string}={children:'uri'})=>{

}

⬇️

// 기본값
const a = (b={children:'uri'})=>{

}
function add<T extends string>(x: T, y: T): T { return x + y }
add(1, 2);
add('1', '2')

// <T extends {...}> // 특정 객체
// <T extends any[]> // 모든 배열
// <T extends (...args: any) => any> // 모든 함수
// <T extends abstract new (...args: any) => any> // 생성자 타입
// <T extends keyof any> // string | number | symbol