最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot set property XXX of undefined in TypeScript - Stack Overflow

programmeradmin3浏览0评论

I want to initialize an interface in TypeScript.

export interface TestGroup {
  "id": number;
  "type": TestType;
  "interval"?: number;
}


import {TestGroup} from "../../gen/api";
public functionConfig: TestGroup;
.
.
.
this.functionConfig.id = testGroup.functionTestConfig;

I get this error:

TypeError: Cannot set property 'id' of undefined

Could you please help me?

I want to initialize an interface in TypeScript.

export interface TestGroup {
  "id": number;
  "type": TestType;
  "interval"?: number;
}


import {TestGroup} from "../../gen/api";
public functionConfig: TestGroup;
.
.
.
this.functionConfig.id = testGroup.functionTestConfig;

I get this error:

TypeError: Cannot set property 'id' of undefined

Could you please help me?

Share Improve this question edited Jun 19, 2017 at 14:26 user663031 asked Jun 19, 2017 at 13:35 SohrabSohrab 1,4884 gold badges16 silver badges35 bronze badges 3
  • you need to initialize functionConfig to some value, right now it is undefiend and you end up doing undefined.id which is not valid javascript. – toskv Commented Jun 19, 2017 at 13:36
  • What is this? Where was this.functionConfig set? Are we supposed to guess? – user47589 Commented Jun 19, 2017 at 13:36
  • Well you declare functionConfig but you don't assign it any value, therefore it is undefined. If you do something like this.functionConfig = { test : "value" } or even just this.functionConfig = { } it will be defined, so afterwards, you can do this.functionConfig.id = "whatever" – Jeremy Thille Commented Jun 19, 2017 at 13:38
Add a ment  | 

2 Answers 2

Reset to default 3

Your functionConfig has a type but it is actually undefined. So you need to initialize it:

public functionConfig: TestGroup = {id: 0, type: 'YourTestTypeHere'};

or your default values for it

Comment

var activateOnWeekDay: Array<boolean> = [];

You can fix it by initializing an empty object {}.

export interface TestGroup {
  id: number;
  type: TestType;
  interval?: number;
}


import {TestGroup} from "../../gen/api";
public functionConfig: TestGroup = {};        <=====Assign empty object
.
.
.
this.functionConfig.id = testGroup.functionTestConfig; 
发布评论

评论列表(0)

  1. 暂无评论