01. Concat
문
Implement the JavaScript Array.concat
function in the type system. A type takes the two arguments. The output should be a new array that includes inputs in ltr order.
For example:
type Result = Concat<[1], [2]> // expected to be [1, 2]
풀이
문제는 다 배열 타입을 하나의 배열로 만드는 문제다. 보는순간 자바스크립트의 spread 문법이 떠올랐고, 바로 적용하니 문제가 해결되어버렸다..!
type Concat<T, U> = ...
// 1. spread 문법을 이용해서 두 배열타입을 나열해준다. 이렇게하면 에러 발생
type Concat<T, U> = [...T, ...U]
// 2. 제한을 걸어서 에러를 해결하자. 제한은 이전에 conditional types 를 하면서 학습했다.
type Concat<T extends unknown[], U extends unknown[]> = [...T, ...U];
참고 레퍼런스를 보니 ...
문법은 타입스크립트 4.0 에 나온 비교적 최신문법이었다.
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types
이 문서를 보고 학습을 더해보자.
Last updated
Was this helpful?