【问题标题】:Type T does not satisfy the constraint C for type parameter P error in TypeScriptType T 不满足 TypeScript 中类型参数 P 错误的约束 C
【发布时间】:2013-09-02 14:33:06
【问题描述】:

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

接口 IViewModel { } 接口 IScope { 虚拟机:TViewModel; // {1} } 接口 IController> { } 类 Controller> 实现 IController { } // {2}

但我在第 {2} 行遇到错误:“类型 'IScope' 不满足类型参数 'TScope extends IScope' 的约束 'IScope' 。”

如果我更进一步并尝试扩展 Controller 类:

接口 IMainViewModel 扩展 IViewModel { } 类主控制器 扩展 Controller> { } // {3}

我在第 {3} 行收到类似错误:“类型 'IScope' 不满足类型参数 'TScope extends IScope' 的约束 'IScope'。”

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

我对 TypeScript 很陌生,我主要用 C# 编写代码,如果我用 C# 编写这段代码 - 只需将 TypeScript 语法重写为它的 C# 等效项,它就可以正常工作。

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

【问题讨论】:

    标签: generics typescript


    【解决方案1】:

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

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

    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 
    } 
    

    看起来像是打字稿编译器错误 (you might want to report it here)。需要明确的是,以下确实有效:

    interface IScope {
        vm: number; // {1}
    }
    
    interface IController<TViewModel, TScope extends IScope> { }
    class Controller<TViewModel, TScope extends IScope>
        implements IController<TViewModel, TScope> {        
    } 
    

    【讨论】:

      猜你喜欢
      • 2015-04-01
      • 2022-10-13
      • 2020-07-07
      • 2020-10-25
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      相关资源
      最近更新 更多