Skip to content

Instantly share code, notes, and snippets.

@tvler
Created March 24, 2021 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvler/abb24584630397054cb8fb12d277554c to your computer and use it in GitHub Desktop.
Save tvler/abb24584630397054cb8fb12d277554c to your computer and use it in GitHub Desktop.
Infer an array argument as a tuple in typescript
// TS playground:
// https://www.typescriptlang.org/play?#code/PTAElByAoAzBXA7AxgFwJYHt6lfaBTAJwBVYAHAGzwB5JRQSK9Q8APZPeAEwGdRvkCOAOYBtALoAaUJAB8ACmRlKALlAiAdJoaUxASlABvWqAJ5FBLIsaQAvgG5IiTP2y5C2vETwuAvK-zESnhyIgDkAIahUqEARlGgoYihepCQwABUtOmgABKETOGmfOgAtkzc5KhCABbkAJ58qCWo5IWgcEhomFmgnHjQOKhd8LzI1eHI7eEtoMjo-oSg4bNBWcCpIKCAvBuA1XswCCgYWIQE6AQAjApBqhqa-ILwomJ6hsam5par9o7Okydn5y8vmYBFOFxCEXisShSRSaTAu32nSOILBACYqB55FYVPQgvojHR3rALCtrN8nCM-qCzmigZM-P8CGiIZFonForDdBsEXsOodMKizgBmTFBZhsDg8PgCYTibHXPGMAlvMwkz7khyUlxM4X00CMmkEYWsqEchJcoA
// ✅
function inferTuple<
Tuple extends string[],
>(tuple: [...Tuple]) {
return tuple
};
const inferTupleTest = inferTuple(['a', 'b', 'c'])
/*
* Here are some slighly similar function
* definitions that fail to infer a tuple
*/
// 🚫
function error1(tuple: [...string[]]) {
return tuple
};
const error1Test = error1(['a', 'b', 'c'])
// 🚫
function error2<Tuple>(tuple: Tuple) {
return tuple
};
const error2Test = error2(['a', 'b', 'c'])
// 🚫
function error3<Tuple extends string[]>(tuple: Tuple) {
return tuple
};
const error3Test = error3(['a', 'b', 'c'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment