4

Apologize for my English first.

I have a function like function func(): [string, string[]] which returns a Tuple. However, when I implement the return statement like

var test = ['text', ['foo', 'bar']];
return test;

Typescript inferred my return type as (string | string[])[] instead of [string, string[]].

Did I missed something or should I need to cast the return object as Tuple explicitly everytime like return <[string, string[]]>['text', ['foo', 'bar']]. If yes then isn't it quite annoying?

Provided the full function as follow:

function func(): [string, string[]] {
    var test= ['text', ['foo', 'bar']];

    return test;
}

Error: Type '(string | string[])[]' is missing the following properties from type '[string, string[]]': 0, 1ts(2739)

enter image description here

2
  • 1
    I cannot reproduce it Commented Mar 15, 2020 at 7:48
  • 1
    1. Please post code, not images of code. 2. Your image example is indeed different - you should have posted that instead. Commented Mar 15, 2020 at 8:17

1 Answer 1

6

TS cannot differentiate, if you want ['text', ['foo', 'bar']] to be an array or a tuple - the expression is the same! It will default to an array for the test variable type, if nothing else specified.

If you want a tuple, do one of the following:

function func(): [string, string[]] {
    const test = ['text', ['foo', 'bar']];
    const test2 = ['text', ['foo', 'bar']] as const;
    const test3: [string, string[]] = ['text', ['foo', 'bar']];
    // return test;   // error, was inferred as array
    // return test2; // works
    return test3; // works
}

With as const you don't have to repeat your type, but you will have to annotate the function return type with readonly modifiers: readonly [string, readonly [string, string]].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.