【问题标题】:I am studying the TS tuples, what's wrong with this code?我正在研究 TS 元组,这段代码有什么问题?
【发布时间】:2019-10-29 00:19:36
【问题描述】:

打字稿元组没有按我的意愿工作。

tsc版本3.6.4

1、当我像下面这样初始化一个元组时:

let x: [string, number];
x[0] = 'John';

并通过tsc得到以下javascript:

var x;
x[0] = 'John';

现在用node 运行,我得到了这个错误:

/home/peng/ts-learnings/dist/tuple.js:2
x[0] = 'John';
     ^

TypeError: Cannot set property '0' of undefined
    at Object.<anonymous> (/home/peng/ts-learnings/dist/tuple.js:2:6)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at internal/main/run_main_module.js:17:11

这是我的tsconfig.json:

{
    "include": [
        "src/*.ts"
    ],
    "compilerOptions": {
        "noImplicitAny": true,
        "target": "es2016",
        "outDir": "dist/",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "types": [
            "reflect-metadata"
        ]
    }
}

请告诉我有什么问题。

2、而且这段代码sn-p也让我很困惑。

type Person = [string, number];
let tom: Person = ['Tom', 35];
tom[0] = 'John';
tom[1] = 25;
tom.pop();
// ['John']
tom.push('test');
// ['John', 'test']

正如一些TS教程所说,语句tom.push('test')不能通过编译器检查,因为tom[1]number的类型!

【问题讨论】:

  • 请说明您的问题
  • 检查 typescript tuple 文档以获取示例
  • @Anna 对不起,我已经阅读了好几遍文档了。

标签: typescript tuples


【解决方案1】:

考虑元组的一种好方法是不要将其真正视为一个数组(即使它是在 javascript 中)。

如果你的元组被指定为[string, number],这意味着它总是必须有一个1个字符串和1个数字,按照这个顺序。不多也不少。

如果您对该元组执行.pop(),您会将项目数减少到1,这意味着它不再是[string, number] 类型。 Typescript 会阻止您这样做,因为 typescript 的目标之一是确保如果您将变量定义为某种类型,它应该始终是该类型。

所以要回答为什么你不能运行.pop(),这实际上意味着'你不能因为你告诉 typescript 你的变量总是[string, number] 的类型。如果您希望能够删除最后一个数字,则需要使用不同的类型。

所以这最终导致了一些 XY 问题。 为什么你要这样做?

至于这个sn-p:

let x: [string, number];
x[0] = 'John';

它不起作用的原因是因为x 没有初始化为数组。它应该更正为:

let x: [string, number];
x = ['John', 25]

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 2015-04-25
    • 2018-09-09
    相关资源
    最近更新 更多