Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between string[] and non-fixed-length string tuple?

Tags:

typescript

import {Equal} from '@type-challenges/utils';
type StringTuple = [string, ...string[]]; // Tuples also support rest elements
let d: StringTuple = ['a', 'b', 'c'];
let e: StringTuple = ['a', 'b', 'c', 'd', 'e'];
type R = Equal<StringTuple, string[]>; // false

What's the difference between StringTuple and string[]? Both of them are non-fixed length arrays of strings, but they are not equal.

UPDATE:

Thanks to @Kelvin Schoofs. I got it:

After remove starting string, StringTuple do equals to string[]!

import {Equal} from '@type-challenges/utils';
type StringTuple = [...string[]]; // Tuples also support rest elements
let d: StringTuple = []; // OK!
let e: StringTuple = ['a', 'b', 'c', 'd', 'e'];
type R = Equal<StringTuple, string[]>; // true!
like image 466
aztack Avatar asked Jul 24 '26 01:07

aztack


1 Answers

Your StringTuple is defined as starting with a string. You can't e.g. assign an empty array (or even string[]!) to a StringTuple variable:

type StringTuple = [string, ...string[]]; // Tuples also support rest elements
let d: StringTuple = ['a', 'b', 'c'];
let e: StringTuple = ['a', 'b', 'c', 'd', 'e'];
let error: StringTuple = [];
// ^ Type '[]' is not assignable to type 'StringTuple'.
//  Source has 0 element(s) but target requires 1.ts(2322)
let error2: StringTuple = (['a', 'b'] as string[]);
// ^ Type 'string[]' is not assignable to type 'StringTuple'.
//  Source provides no match for required element at position 0 in target.ts(2322)
like image 164
Kelvin Schoofs Avatar answered Jul 25 '26 18:07

Kelvin Schoofs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!