我正在尝试为JS类实现DefinitelyTyped TS定义文件,该类具有不同的定义,具体取决于它的实例化方式。定义很明确,在实例化后不会改变 例如:
var a = new MyClass("foo");
console.log(a.a);//"a"
console.log(a.b);//"b"
console.log(a.c);//"c"
console.log(a.d);//"undefined"
console.log(a.e);//"undefined"
console.log(a.f);//"undefined"
var b = new MyClass("bar");
console.log(b.a);//"undefined"
console.log(b.b);//"undefined"
console.log(b.c);//"c"
console.log(b.d);//"d"
console.log(b.e);//"e"
console.log(b.f);//"f"
我想要一个类似于TS的定义:
interface myInterface{
c:string;
}
class MyClass("foo") implements myInterface{
a:string;
b:string;
c:string;
}
class MyClass("bar") implements myInterface{
c:string;
d:string;
e:string;
f:string;
}
任何指针都将非常感谢
编辑:澄清:我无法修改MyClass
此外,有许多不同的实例化MyClass
的方法,但它们都是众所周知的,并且提前定义。我们还可以假设我们不必担心MyClass
的非存在变异的情况
此外,MyClass
最好被描述为允许访问数据库的工厂;所以new MyClass("foo")
会创建一个对象,允许访问数据库中的 foo 表,其中字段名称现在是创建的MyClass
对象的属性
答案 0 :(得分:-1)
如果您可以控制代码......
您应该考虑修复它。你描述的是两种不同的类型,根据输入参数改变类的类型没有多大意义。
您的示例中的MyClass
看起来像某种奇怪的工厂,它使用构造函数而不是方法来创建对象。
代码中的解决方案可能看起来像使用联合类型和类型保护:
class Foo {
public FooMember: string = "I'm foo";
}
class Bar {
public BarMember:string = "I'm bar";
}
let myObj: Foo | Bar;
myObj = new Foo(); // or FooBarFactory.GetInstance("Foo") or whatever
if(myObj instanceof Foo){
console.log(myObj.FooMember);
} else {
console.log(myObj.BarMember);
}
如果您无法控制代码......
...你基本上没有运气,因为它根据构造函数的输入而输入不同。您不能键入类的构造函数以返回除类的类型之外的任何内容。