javascript – 使用Typescript强制接口的泛型约束?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 使用Typescript强制接口的泛型约束?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2316字,纯文字阅读大概需要4分钟。
内容图文
我有2个接口声明:
interface IStore { }
interface SomethingElse { a: number;}
实现每个的2个类:
class AppStoreImplemetion implements IStore
{ }
class SomethingImplementation implements SomethingElse
{
a: 4;
}
我希望我的方法被赋予返回类型作为“必须是IStore”的约束,所以我这样做:
class Foo {
selectSync<T extends IStore>( ): T
{
return <T>{/* omitted*/ }; // I set the return type(`T`) when invoking
}
}
好
测试:
这按预期工作:
new Foo().selectSync<AppStoreImplemetion>();
但这也有效 – 不像预期的那样:
new Foo().selectSync<SomethingImplementation>();
题:
如何强制我的方法接受必须实现IStore的返回类型?
解决方法:
问题是Typescript使用结构类型来确定类型兼容性,因此接口IStore是空的,与任何其他类型兼容,包括SomethingElse
模拟标称类型(在C#/ Java等中的类型)的唯一方法是添加一个使接口与其他接口不兼容的字段.您实际上不必使用该字段,您只需声明它以确保不兼容:
interface IStore {
__isStore: true // Field to ensure incompatibility
}
interface SomethingElse { a: number; }
class AppStoreImplemetion implements IStore {
__isStore!: true // not used, not assigned just there to implement IStore
}
class SomethingImplementation implements SomethingElse {
a = 4;
}
class Foo {
selectSync<T extends IStore>(): T {
return <T>{/* omitted*/ };
}
}
new Foo().selectSync<AppStoreImplemetion>();
new Foo().selectSync<SomethingImplementation>(); // This will be an error
请注意,任何具有__isStore的类都将兼容,无论它显式实现IStore的天气如何,同样由于Typescript使用结构来确定兼容性,因此这是有效的:
class SomethingImplementation implements SomethingElse {
a = 4;
__isStore!: true
}
new Foo().selectSync<SomethingImplementation>(); // now ok
在实践中,IStore可能会有更多的方法,因此这种偶然的兼容性应该是非常罕见的.
正如旁注,私有字段确保100%不相关的类不兼容,因此如果可以使IStore成为具有私有字段的抽象类.这可以确保没有其他类意外兼容:
abstract class IStore {
private __isStore!: true // Field to ensure incompatibility
}
interface SomethingElse { a: number; }
class AppStoreImplemetion extends IStore {
}
class Foo {
selectSync<T extends IStore>(): T {
return <T>{/* omitted*/ };
}
}
new Foo().selectSync<AppStoreImplemetion>(); // ok
class SomethingImplementation implements SomethingElse {
private __isStore!: true;
a = 10;
}
new Foo().selectSync<SomethingImplementation>(); // an error even though we have the same private since it does not extend IStore
内容总结
以上是互联网集市为您收集整理的javascript – 使用Typescript强制接口的泛型约束?全部内容,希望文章能够帮你解决javascript – 使用Typescript强制接口的泛型约束?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。