您好, typewriter 专家.

我有以下代码,但我必须在类中重复接口属性,否则我会得到:

类错误地实现了接口

在使用接口时,是否有一个TypeScript速记来实现这一点,而不必声明Id: number;和类中的所有其他属性?谢谢

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中使用类/接口合并就可以实现这一点.

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相关问答推荐

SortKey类型不起作用,尽管它使用的单个类型工作正常<>'

在Angular中注入多个BrowserModules,但在我的代码中只有一个

在MessageStore对象中实现条件类型时出现TypeScrip错误

如何编写一个类型脚本函数,将一个对象映射(转换)为另一个对象并推断返回类型?

使用TypeScrip根据(可选)属性推断结果类型

使用打字Angular 中的通用数据创建状态管理

为什么在这个例子中,我把缺少的属性添加到对象中时,TypeScrip没有拾取,如何修复?

如何消除在Next.js中使用Reaction上下文的延迟?

有没有可能为这样的函数写一个类型?

react 路由Use RouteLoaderData类型脚本错误

布局组件中的Angular 17命名路由出口

为什么S struct 类型化(即鸭子类型化)需要非严格类型联合?

TypeScrip-如何自动推断UNION变量的类型

声明遵循映射类型的接口

如何定义这样一个TypeScript泛型,遍历路由配置树并累积路径

如何在Type脚本中创建一个只接受两个对象之间具有相同值类型的键的接口?

Typescript不允许在数组中使用联合类型

类型分布在第一个泛型上,但不分布在第二个泛型上

Next 13 + React 18 createContext 类型的构建问题

如何在由函数参数推断的记录类型中具有多个对象字段类型