Created
March 24, 2021 21:30
-
-
Save tvler/abb24584630397054cb8fb12d277554c to your computer and use it in GitHub Desktop.
Infer an array argument as a tuple in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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