Issue
I have a function that takes one argument and returns it as it is:
function test<T>(input: T): T {
return input
}
I found that if I pass a number or string, the returned type is going to be a literal type
const res = test(1) // 1
const input = 1
const res2 = test(input) // 1
But if I slightly change the function to make it return a tuple:
function test2<T>(input: T): [T] {
return [input]
}
then the return type becomes just the string
or number
type:
const res3 = test2(1) // [number]
So here I have two questions:
- Why does the
test
function return literal types? Are there any resources I can read to learn this behaviour? - Why is it that wrapping the return value into a tuple solves this?
Solution
why is the
test
function returns literal types? Are there any resources I can read to learn this behaviour?
TypeScript infers primitive types. You can read about function parameter type inference here:
https://www.typescriptlang.org/docs/handbook/2/functions.html#inference
why is that wrapping the return value into a tuple solves this?
TypeScript doesn’t (yet) infer tuples
Answered By – jsejcksn
Answer Checked By – Mildred Charles (BugsFixing Admin)