类型T不满足TypeScript中类型参数P错误的约束C

类型T不满足TypeScript中类型参数P错误的约束C

本文介绍了类型T不满足TypeScript中类型参数P错误的约束C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在TypeScript中实现这一点:

I'm trying to implement this in TypeScript:


interface IViewModel { }
interface IScope<TViewModel extends IViewModel> {
    vm: TViewModel; // {1}
}
interface IController<TViewModel extends IViewModel, TScope extends IScope<TViewModel>> { }

class Controller<TViewModel extends IViewModel, TScope extends IScope<TViewModel>>
    implements IController<TViewModel, TScope> { } // {2}

但是在行{2}上出现错误:类型'IScope< TViewModel扩展了IViewModel>''不满足约束条件"IScope< TViewModel扩展IViewModel>".类型参数"TScope扩展了IScope< TViewModel>"."

but I'm getting an error on line {2}: "Type 'IScope<TViewModel extends IViewModel>' does not satisfy the constraint 'IScope<TViewModel extends IViewModel>' for type parameter 'TScope extends IScope<TViewModel>'."

如果我走得更远并尝试扩展Controller类:

If I go further and try to extend the Controller class:


interface IMainViewModel extends IViewModel { }

class MainController
    extends Controller<IMainViewModel, IScope<IMainViewModel>> { } // {3}

在行{3}上我收到类似的错误:"Type'IScope< IMainViewModel>'"不满足约束条件"IScope< TViewModel扩展了IViewModel>".类型参数"TScope扩展了IScope< TViewModel>"."

I get a similar error on line {3}: "Type 'IScope<IMainViewModel>' does not satisfy the constraint 'IScope<TViewModel extends IViewModel>' for type parameter 'TScope extends IScope<TViewModel>'."

在我看来这应该可行.我在做什么错了?

Seems to me that this should work. What am I doing wrong?

我是TypeScript的新手,我主要用C#编写代码,如果我用C#编写此代码-只需将TypeScript语法重写为等效的C#,就可以了.

I'm pretty new to TypeScript, I mainly write code in C#, and if I write this code in C# - by just rewriting TypeScript syntax to its C# equivalent, it works just fine.

最奇怪的是,如果我删除第{1}行,这两个错误都会消失.

The weirdest thing is that if I remove line {1}, both errors disappear.

推荐答案

Typescript接口是结构化的.这就解释了为什么当您从{1}中删除唯一的项目时,您不会再出现任何错误,因为任何东西都将与空接口兼容.

Typescript interfaces are structural. That explains why when you removed the only item from {1} you don't get any errors anymore because any thing would be compatible with an empty interface.

说以下内容也应该起作用:

That said the following should also work:

interface IScope<TViewModel> {
    vm: TViewModel; // {1}
}

interface IController<TViewModel, TScope extends IScope<TViewModel>> { }
class Controller<TViewModel, TScope extends IScope<TViewModel>>
    implements IController<TViewModel, TScope> { // Gets an error
}

看起来像是打字稿编译器错误(您可能要在这里报告它).需要明确的是,以下方法确实有效:

Looks like a typescript compiler error (you might want to report it here). To be clear the following does work:

interface IScope {
    vm: number; // {1}
}

interface IController<TViewModel, TScope extends IScope> { }
class Controller<TViewModel, TScope extends IScope>
    implements IController<TViewModel, TScope> {
}

这篇关于类型T不满足TypeScript中类型参数P错误的约束C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:29