简体   繁体   English

为什么方法 push() 有下划线?

[英]Why is method push() underlined?

So hello for the first, I tried to make a little imaginary shopping cart for exercise in TypeScript.首先,你好,我试着用 TypeScript 制作一个想象中的购物车来锻炼。 So i did and now I have a question here is the code.所以我做了,现在我有一个问题是代码。

class Warenkorb {
    liste:string[];

    add(produkt):void{
        this.liste.push(produkt);
    }
}

This is the first one it works fine no underlinings.这是第一个它工作正常没有下划线。

class Warenkorb {
    liste:string|number[];

    add(produkt):void{
        this.liste.push(produkt);
    }
}

So this the problem.所以这就是问题所在。 When i want number or string the push method is red underlining it is not a problem for the exercise because the products should be only strings but i also want to know why it is so.当我想要数字或字符串时,push 方法是红色下划线,这对练习来说不是问题,因为产品应该只是字符串,但我也想知道为什么会这样。

And sorry for the bad variable names i am german/austrian :D很抱歉我是德国人/奥地利人的坏变量名:D

Both of those should be showing you errors, because produkt implicitly has the type any .这两个都应该向您显示错误,因为produkt隐式具有类型any

The problem with list is that it's a string , or a number[] . list的问题在于它是一个string或一个number[] If you want it to allow both strings and numbers, you need (string | number)[] .如果您希望它同时允许字符串和数字,则需要(string | number)[]

You also need to initialize liste with an empty array.您还需要使用空数组初始化liste

So:所以:

class Warenkorb {
    liste: (string|number)[] = [];
// −−−−−−−−^−−−−−−−−−−−−−^   ^^^^−−−−−−−−−−−−
    add(produkt: string|number):void{
// −−−−−−−−−−−−^^^^^^^^^^^^^^^
        this.liste.push(produkt);
    }
}

The syntax is not correct in second example, you need to add array for both data types in union like below:第二个示例中的语法不正确,您需要为联合中的两种数据类型添加数组,如下所示:

class Warenkorb {
liste:string[]|number[] = [];

add(produkt):void{
    this.liste.push(produkt);
}

Now you are defining that it will be either array of strings or array of numbers and initialize with an empty array, else it will have default value of undefined and an error will occur.现在您正在定义它将是字符串数组或数字数组并使用空数组进行初始化,否则它将具有未定义的默认值并且会发生错误。

In your case you define it either to be string or array of numbers.在您的情况下,您将其定义为字符串或数字数组。 So push method does not exist on strings.所以字符串上不存在 push 方法。

string|number[]

The notation you wrote says: liste is of type string or number[] .你写的符号说: liste 是stringnumber[]类型。

This is what you tried to say这就是你想说的

class Warenkorb {
  liste: (string|number)[];

  add(produkt: string|number):void {
    this.liste.push(produkt);
  }
}

As a side note, if you were to enable strict mode.附带说明一下,如果您要启用严格模式。 You would get another error.你会得到另一个错误。 One that would say that "liste" is not defined in the constructor.一个会说“liste”没有在构造函数中定义的。 You either should use liste: (string|number)[] = [] , or create constructor and assign it there.您应该使用liste: (string|number)[] = [] ,或者创建构造函数并在那里分配它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM