打字稿覆盖通用属性

时间:2019-03-25 19:37:10

标签: typescript

我有以下代码:

class Base<T> {}

class Test {
  prop: Base<any>;

  createProp<T>() {
    this.prop = new Base<T>();
  }
}

const test = new Test();

test.createProp<{ a: number }>();

test.prop // Base<any> expected Base<{ a: number }>

当我使用泛型调用createProp时,我希望它成为prop属性的新类型。当前,运行此方法后,类型仍为-Base<any>。有没有办法用TS做到这一点?

1 个答案:

答案 0 :(得分:1)

prop被定义为Base<any>-即使分配了Base<T>,也永远不会是class Base<T> {} class Test<T> { prop: Base<T>; createProp() { this.prop = new Base<T>(); } } const test = new Test<{ a: number }>(); test.createProp(); test.prop

要实现此行为,您必须使您的 class 泛型,而不仅仅是方法:

class Base<T> {}

class Test {
  prop: Base<any>;

  createProp<T>() {
    this.prop = new Base<T>();
  }
}

const test = new Test();

test.createProp<{ a: number }>();

test.prop as Base<{ a: number }>
// --- or ---
<Base<{ a: number }>> test.prop

或者,如果您真的反对使用泛型类,则可以使用type assertion

Sub SetClip(sContents)
  Dim WshShell: Set WshShell = CreateObject("WScript.Shell")
  WshShell.Run "cmd.exe /c echo " & sContents & " | clip", 0, TRUE
  WshShell.SendKeys "%{TAB}",True
  Call Pause(.1) 'This is my current method of waiting on the window.
  WshShell.SendKeys "^v"
  WshShell.Run "cmd.exe /c echo off | clip", 0, TRUE 'clear clipboard
  Set WshShell = nothing
End Sub