javascript - How to push string to typescript array? - Stack Overflow

I am trying to push string to typescript array its throwing error `can not push to undefined" , is

I am trying to push string to typescript array its throwing error `can not push to undefined" , is it correct way or i need to use spread operator ?

api.ts

const api: IConfigName = {name: "getKey"};
const Name = "Web";

api.optionalParam.push(Name);

IConfig.interface.ts

export interface IConfigName {
    name: string;
    optionalParam?: string[];
}

I am trying to push string to typescript array its throwing error `can not push to undefined" , is it correct way or i need to use spread operator ?

api.ts

const api: IConfigName = {name: "getKey"};
const Name = "Web";

api.optionalParam.push(Name);

IConfig.interface.ts

export interface IConfigName {
    name: string;
    optionalParam?: string[];
}
Share Improve this question asked May 1, 2018 at 16:26 hussainhussain 7,14121 gold badges87 silver badges165 bronze badges 1
  • can not push to undefined is not a real error, please post the actual error message. Are you seeing a runtime JavaScript error, or a pile-time TypeScript error? Are you using strictNullChecks? – Aaron Beall Commented May 1, 2018 at 17:25
Add a ment  | 

2 Answers 2

Reset to default 5

You need to initialize optionalParam with empty array as follows,

api.optionalParam = [];
api.optionalParam.push(Name);

You are getting this because there is no "optionaParam" defined in your api object.

your api object currently has only one other, which is "name"

to fix, you can add optionalParam like such:

const api: IConfigName = {name: "getKey", optionalParam:[] };
const Name = "Web";

api.optionalParam.push(Name);

this should work, since api now has an optionalParam key, with a type of array.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745195497a4616067.html

相关推荐

  • javascript - How to push string to typescript array? - Stack Overflow

    I am trying to push string to typescript array its throwing error `can not push to undefined" , is

    1小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信