TypeScript - Intersection&Union

Seung min, Yoo·2021년 5월 7일
0
post-thumbnail
interface User {
  name: string;
}
interface Action {
  do(): void;
}

intersection타입은 여러 타입을 합쳐진 타입을 말한다.
위의 interface를 intersection 타입으로 만들어 보자.

interface User {
  name: string;
}
interface Action {
  do(): void;
}

function createUserAction(u: User, a: Action): User & Action {
  return {...u, ...a};
}

const u = createUserAction ({ name: 'jay' }, { do() {} });
u. //intersection을 통해서 두 타입이 합쳐지고 'u.'을 통해서 두 타입을 이용할 수 있다

union type

function compare(x: string | number, y: srting | number) {
//x.을 입력해보면 string과 number 두 타입에서 같이 존재하는 멤버들만 나오게 된다.
  if (typeof x === 'number' && typeof y === 'number') {
   //x. 을 입력해보면 x가 number타입으로 인식하게 된다. 왜냐하면 typeof연산자로 타입에 대해서 검증해줬기 때문이다.
    return x === y ? 0 : x > y ? 1 : -1; 
  }
  if (typeof x === 'string' && typeof y === 'string') {
    return x.localCompare(y);
  }
  throw Error ('not support type');
}
const v = compare(1, 2);
console.log([3, 2, 1].sort(compare))
console.log(['c', 'b', 'a'].sort(compare))

compile to

[1 ,2 ,3]
['a', 'b', 'c']

or기호를 사용해서 표현하는 것이 union타입이다.

interface를 만약 union타입을 했을 경우 어떤 일이 일어나는지 보자

function compare(x: string | number, y: srting | number) {
  if (typeof x === 'number' && typeof y === 'number') {
    return x === y ? 0 : x > y ? 1 : -1; 
  }
  if (typeof x === 'string' && typeof y === 'string') {
    return x.localCompare(y);
  }
  throw Error ('not support type');
}
const v = compare(1, 2);
console.log([3, 2, 1].sort(compare))

function process(v: User | Action) {
  if(v.do) //멤버가 있는지 체크하면 되는데, v라는 값에 do가 있는지 보려고 하면 v는 union타입이기 때문에 do타입의 공통된 멤버에만 접근할 수 있다. 공통된 멤버가 아니기 때문에 do라는 속성이 없다고 나온다.
   //이렇게 assertion하면 된다.
  if((<Action>v).do) {
    v.do//여기서도 아직 타입 가드가 된 것이 아니다 assertion한 것이기 때문에 여기서도 type assertion을 해야 한다.
    //이렇게 assertion하면 된다.
    	(<Action>v).do()
  }
}

//우리가 매번 typeassertion을 할 수 없기 때문에 타입가드를 만들어보자
function isAction(v: User | Action): v is Action//v라는 타입가드를 is를 통해서 설정할 수 있다. {
  return (<Action>v).do !== undefined;
}

function process(v: User | Action) {
  if(isAction(v)) {
    v.do() // Action이라고 인지한다.
  } else {
    console.log(v.name);
  }
}

위에서 사용자 정의 타입가드를 확인할 수 있다

profile
이제 막 개발을 시작한 프로그래밍 입문자

0개의 댓글