0

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[];
}
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 compile-time TypeScript error? Are you using strictNullChecks? Commented May 1, 2018 at 17:25

2 Answers 2

5

You need to initialize optionalParam with empty array as follows,

api.optionalParam = [];
api.optionalParam.push(Name);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you it worked i need to think again i am working with typescript now :)
2

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.

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.