Typescript inferring Tuple as Array Incorrectly

时光怂恿深爱的人放手 提交于 2021-02-05 12:06:04

问题


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)


回答1:


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:

  • use a const assertion
  • give test an explicit tuple type
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]].



来源:https://stackoverflow.com/questions/60690688/typescript-inferring-tuple-as-array-incorrectly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!