Typescript 튜플 유형

Typescript 4.2 이상에서 튜플을 가장 잘 입력하는 방법

Typescript 튜플 자세히 살펴보기

다시 말해 가장 기본적인 정의의 튜플은 여러 부분으로 구성된 데이터 구조 일뿐입니다. Typescript와 같은 프로그래밍 언어에서 튜플을 사용하는 범위에서 데이터가 가장 일반적으로 정렬된다는 점도 중요합니다.

간단한 예제는 Typescript에서 튜플을 정의하는 방법을 보여줍니다.

// This tuple is defined as a set
// of two numbers.
const scores: [number, number] = [1, 2];

// For comparison, this tuple consists
// of three elements, each of a different
// type. Not that the ordered nature of
// tuples in TS becomes very clear here.
const result: [string, number, boolean] = ["id", 101, false];

// And as a "nice-to-know", you can even
// provide lables for the tuple elements.
// This doesn't have any effect on the typesystem
// itself and only (may) improve documentation.
const output: [id: number, name: string] = [101, "Tom"];

선택적 요소가있는 튜플

Typescript가 시간이 지남에 따라 개선됨에 따라 튜플 구현도 향상되었습니다. 필수 요소 만 정의 할 필요는 없습니다. 이제 요소를 선택 사항으로 입력 할 수도 있습니다. 모르는 경우 Typescript는 물음표를 일반 기호로 사용하여 요소를 선택 사항으로 정의합니다. 즉, 런타임에 사용할 수 있지만 반드시 그럴 필요는 없습니다.

또 다른 예는 내가 의미하는 바를 보여줍니다.

// Similar to our previous example, but in this
// case the the tuple's last element doesn't have
// to be provided (or can be undefined at runtime).
type Tuple = [id: number, name?: string];

const a: Tuple = [101];
const b: Tuple = [42, "Tom"];

Typescript 튜플의 나머지 요소

나머지 요소를 사용하면 주어진 유형의 튜플에서 다음 요소를 모두 표시하는 매우 강력한 유형이 있습니다. 두 개의 요소가있는 튜플과 나머지 요소로 정의 된 두 번째 요소가 있다고 가정하면 런타임에이 튜플 변수에 2 + n 요소를 제공 할 수 있습니다.

정의의 범위를 좁히기 위해 최근까지 이러한 요소는 튜플의 끝에서만 허용되었습니다. 이것은 나머지 유형의 런타임에 여러 요소를 제공 할 수 있도록 허용하지만 나머지 요소와 하나 이상의 다른 유형 항목을 구별하기가 매우 복잡해 지므로 의미가 있습니다.

// This example might be a tuple type
// for a CLI similar to Node.js. The first
// two elements are system-internal.
//
// Starting from the 3rd element, a user can
// provide as much arguments as desired, yet
// we can still cleanly handle it with TS. Nice!
let input: [number, boolean, ...string[]];

// Just to show that we really can provide any
// number of rest elements, including 0.
e = [0, false, "max-cache", "1024", "debug", "false"];
e = [0, false];
e = [0, false, "verbose"];

튜플 형식의 선행 또는 중간 나머지 요소

튜플의 나머지 요소를 발전 시키면 Typescript 4.2가 출시 된 이후 더 정교한 구현을 만들 수 있습니다. 그리고 저는 여기서 사과해야합니다. 몇 문장 만 일찍부터 마지막으로 만 나머지 요소를 사용하는 것이 의무적 인 방법을 썼습니다. 이 제한은 Typescript 4.2 이후로 더 이상 사실이 아닙니다. 이제 튜플의 거의 모든 곳에 나머지 요소를 배치 할 수 있기 때문입니다.

그러나 몇 가지 제한 사항으로 Typescript는 이제 고급 튜플을위한 매우 멋진 구문을 제공합니다. Rest 요소는 다음 두 규칙을 준수하는 한 튜플 내의 어느 곳에서나 발생할 수 있습니다.

  • 뒤에 선택적 요소가 없습니다.
  • 첫 번째 요소 뒤에 다른 나머지 요소가 없습니다.

이론을 너무 많이 이야기하기 전에 예를 들어 보겠습니다.

// And here comes the fancy part: rest elements
// *not only* at the end of a tuple.
// 
// Note: this example is taken directly from the
// TS documentation. For more details, check out the
// links in the addendum.
let foo: [...string[], number];

foo = [123];
foo = ["hello", 123];
foo = ["hello!", "hello!", "hello!", 123];

let bar: [boolean, ...string[], boolean];

bar = [true, false];
bar = [true, "some text", false];
bar = [true, "some", "separated", "text", false];

// And here's an example that shows how the
// type system would catch your errors:
interface Clown { /*...*/ }
interface Joker { /*...*/ }

let StealersWheel: [...Clown[], "me", ...Joker[]];
//                                    ~~~~~~~~~~ Error!
// A rest element cannot follow another rest element.

let StringsAndMaybeBoolean: [...string[], boolean?];
//                                        ~~~~~~~~ Error!
// An optional element cannot follow a rest element.

이 기사의 나머지 요소

Typescript의 튜플에 대한이 간단한 가이드를 마치면서 기본 구현을 살펴본 다음 몇 가지 고급 예제를 통해 Typescript가 튜플에 대해 매우 유연한 유형 시스템을 허용하는 방법을 확인했습니다. 기사를 재미있게 보셨기를 바라며 더 자세히 알고 싶으시면 아래의 다른 추천 게시물을 확인하세요.

제안

관련된

부록

언어