Typescript Angular2接口“找不到名称[interfacename]”

时间:2016-03-15 15:23:29

标签: typescript angular

我有一个如此定义的界面:

import {AppBuild} from '../models/app-build.model'

export interface Build {
    "Name": string
    "Builds"?: Array<AppBuild>
}

在我的组件中,我已导入它:

import {Build} from '../../models/build.model'

但是当我尝试将变量声明为Build

build:Build;
build.Name = "Hi";

我得到Cannot find name 'Build'.

为什么会这样?

如果有帮助,这就是整个功能:

let build:Build = new Build();
build.Name = "Hi";
console.log(buildNumber)
let tempBuildArray = new Array<Build>();

return build;

2 个答案:

答案 0 :(得分:0)

你可能错过了&#39;让&#39;或者&#39; var&#39;关键字,并希望像这样编写变量声明:

let build: Build;
//...Initialize your build variable with value here
build.Name = "Hi";

[编辑]

如果你坚持要建立&#39;作为界面,您可以像这样初始化它:

let build: Build;
build = {Name: '123'};
build.Name = "Hi";

或者你可以把它变成课堂:

export class Build 
{
    public Name: string;
    public Builds: Array<AppBuild>;

    constructor(name: string)
    {
         this.Name = name;
    }
}

以后:

let build: Build;
build = new Build('123');
build.Name = "Hi";

希望这有帮助。

答案 1 :(得分:0)

你不能“新”一个界面。这就是你在这条线上遇到的问题;

let build:Build = new Build(); <----

只能实例化类。所以你必须创建一个“实现”Build接口的类,如下所示;

export class BuildImp implements Build
{
    public Name: string;
    public Builds: Array<AppBuild>;

    constructor(name: string)
    {
         this.Name = name;
    }
}

所以你的代码看起来像这样;

let build:Build = new BuildImp(); // <-- use BuildImp
build.Name = "Hi";
console.log(buildNumber)
let tempBuildArray = new Array<Build>();

return build;