导出从 typeScript 中的类中删除接口实现
我有带有类声明的.ts文件和带有接口声明的.d.ts文件。
.ts 文件示例:
class A {
constructor() {
this.name = "Jo";
}
}
.d.ts 文件示例:
interface A {
name: string
}
所以,问题是 - 一切正常,A 类自动检测接口 A 并实现它。
但是,当我添加类命名导出或默认导出时,如下面的示例所示 - 接口实现消失,再次清楚的是 A 类。
export default class A {
constructor() {
this.name = "Jo";
}
}
或
class A {
constructor() {
this.name = "Jo";
}
}
export { A }
两个变体都会导致相同的问题 - ”类型“A”上不存在属性“名称””。
如果将接口添加到同一文件中,它将可以工作,但我需要此接口进行全局使用,并且不想直接在类或同一文件中编写相同的实现。
那么,到底发生了什么事,我应该怎样做才能让事情恢复正常?
I have .ts file with class declaration and .d.ts file with interface declaration.
.ts file example:
class A {
constructor() {
this.name = "Jo";
}
}
.d.ts file example:
interface A {
name: string
}
So, the problem is - everything working fine, class A auto detect interface A and implements it.
But, when i add class named export or default export, like in example below - interface implementation disappearing, it's again clear class A.
export default class A {
constructor() {
this.name = "Jo";
}
}
or
class A {
constructor() {
this.name = "Jo";
}
}
export { A }
Both variants leads to same problem - "Property 'name' does not exist on type 'A'".
If add interface to same file it will works, but i need this interface for global using and don't want to write same implementation directly in the class or same file.
So, what is going on and what should i do to make things right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当我把你的代码放在 打字稿游乐场 我收到此错误:
如果您遵循该建议:
它会按照您的预期工作Playground
但是,如果
class A
所在的文件是 Typescript,那么您不需要.d.ts
文件,你的类应该是:这是它自己的隐式接口:
游乐场
When I put your code on a typescript playground I get this error:
And if you follow that advice:
It works as you expect Playground
However, if the file that
class A
is in is Typescript, then you don't need the.d.ts
file at all and you class should just be:Which is it's own interface implicitly:
Playground
在
.d.ts
文件中编写接口并与同名类冲突属性是最不常见的。惯用的做法是将接口编写在一个文件中:
然后将其导入另一个文件中,并通过
implements
关键字正确使用它:当然,您可以将完全相同的接口导入到任何其他文件中文件。全球化很少能带来最好的结果。
It's most unusual to write your interfaces in
.d.ts
files and to collide properties with a same-named class.The idiomatic was to do this is to write the interface in one file:
and import it in another and use it correctly via the
implements
keyword:You can, of course, import the very same interface into any other file. Making things global rarely works out for the best.