Typescript 自动获取类中的接口属性 [英] Typescript automatically get interface properties in a class
本文介绍了Typescript 自动获取类中的接口属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好 TypeScript 专家.
Hello TypeScript experts.
我有以下代码,但我必须在类中重复接口属性,否则我会得到:
I have the following code but I have to repeat the interface properties in the class otherwise I get:
类错误地实现了接口
在使用接口时,是否有 TypeScript 的简写,无需声明 Id: number;
和类中的所有其他属性?谢谢
When using an interface, is there a TypeScript shorthand for doing this without having to declare Id: number;
and all the other properties in the class? Thx
interface INavigation {
Id: number;
AppId: number;
NavId: number;
Name: string;
ParentId: string;
PageURL: string;
Position: string;
Active: string;
Desktop: string;
Tablet: string;
Phone: string;
RoleId: string;
Target: string;
}
class Navigation implements INavigation {
Id: number;
AppId: number;
NavId: number;
Name: string;
ParentId: string;
PageURL: string;
Position: string;
Active: string;
Desktop: string;
Tablet: string;
Phone: string;
RoleId: string;
Target: string;
constructor(navigation: any) {
this.Id = navigation.Id
this.AppId = navigation.NavAppId
this.NavId = navigation.NavId
this.Name = navigation.NavName
this.ParentId = navigation.NavParentId
this.PageURL = navigation.NavPageURL
this.Position = navigation.NavPosition
this.Active = navigation.NavActive
this.Desktop = navigation.NavDesktop
this.Tablet = navigation.NavTablet
this.Phone = navigation.NavPhone
this.RoleId = navigation.NavRoleId
this.Target = navigation.NavTarget
}
}
推荐答案
现在可以在 Typescript 中使用类/接口合并.
This is now possible in Typescript using class/interface merging.
interface Foo {
a: number;
}
interface Baz extends Foo { }
class Baz {
constructor() {
console.log(this.a); // no error here
}
}
https://github.com/Microsoft/TypeScript/issues/340#issuecomment-184964440
这篇关于Typescript 自动获取类中的接口属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文