2017-11-25 110 views
1

我有一个接口:如何在对象Typescript中使用这个描述符?

export interface DisabledFormFields { 
    active: number, 
    functions: { 
    get?($event: any): string; 
    set?($event: any): void; 
    } 
} 

然后我创建基于此intreface对象:

instance.set({index: 0}); 
instance.get({}); 

为什么我不能获得财产active使用:

var instance = { 
    active: 0, 
    set(event) { 
     this.active = event.index; 
    }, 
    get(event) { 
     return "-"; 
    }, 
} 

使用此this描述符里面的方法对象?

+3

你会得到什么错误?我看到的第一件事是接口和对象不匹配。 (函数子对象丢失) –

+0

为什么你用两个不同版本的TypeScript标记了这个? – Amy

+0

没有任何错误 – Oleg

回答

2

你(轻微改变)对象:

var instance: Disable = { 
    active: 0, 
    set(event: any) { 
     this.active = event.index; 
    }, 
    get(event: any) { 
     event;// doing nothing but dealing with the noUnusedParameteres 
     return "-"; 
    }, 
} 

能有这样的接口:

interface Disable { 
    active: number; 
    set?(event: any): void; // not necessarily optional 
    get?(event: any): string;// idem 
} 

如果set和get是可选的,它是需要使用型后卫,看看他们是定义:

if(instance.set) { 
    instance.set({index: 1});// it is defined in this block 
} 

在您的原始界面中,您有这个内部对象...

functions: { 
    get?($event: any): string; 
    set?($event: any): void; 
} 

你没有包含在你的对象中。该对象也没有实现该接口,因为结构不同,并且在var声明中没有注释。你必须改变界面或你的对象。

+0

我真的不明白你的解决方案,对我来说,这是我发布的相同。它在对象内部没有作用:'this.active = event.index;' – Oleg

+0

它看起来是一样的,因为它是相同的(因此稍微改变了)。它只是给出了一些想法,为什么你的界面在这种情况下没有用处。尝试移除界面,不要声明类型,只需使用已定义的对象。如果它给出了一些编译错误,请更新错误代码的问题,如“TS1234出错了” – 2017-11-25 22:09:46

+0

您可以尝试在这里,它不起作用:https://www.typescriptlang.org/play/ – Oleg

1

我用的操场和尝试这个

var instance = { 
    active: 0, 
    set(event) { 
     this.active = event.index; 
    }, 
    get(event) { 
     return "<h1>-</h1>"; 
    }, 
} 

instance.set({index: 0}); 
instance.get({}); 

document.writeln(instance.get({})); 

它transpiled这样:

var instance = { 
    active: 0, 
    set: function (event) { 
     this.active = event.index; 
    }, 
    get: function (event) { 
     return "<h1>-</h1>"; 
    }, 
}; 
instance.set({ index: 0 }); 
instance.get({}); 
document.writeln(instance.get({})); 

而且在运行单击时在浏览器中打开一个新的标签与此:

-

+0

操场可能没有进行所有严格的类型检查,因为它没有拒绝没有类型注释的_event_参数。 – 2017-11-25 22:26:47

相关问题