[英]How to type parameters of a function exposed in a TypeScript library consumed by JavaScript code?
I am creating a library written in Typescript which expose a class with a constructor that accept one parameter of type Set
. 我正在创建一个用Typescript编写的库,它暴露了一个带有构造函数的类,该构造函数接受一个类型为
Set
参数。
This library will be used by a application written in javascript, I need to check that the parameter is a valid Set
. 这个库将由javascript编写的应用程序使用,我需要检查该参数是否为有效
Set
。 My code currently looks something like that: 我的代码目前看起来像这样:
export class Something {
private mySet: Set<string>;
constructor(aSet: Set<string>) {
if (!(aSet instanceof Set)) {
throw new TypeError('Invalid parameter');
}
this.mySet = aSet;
}
}
I created a test suite that checks this code: 我创建了一个检查此代码的测试套件:
it('should throw if instantiate without parameter', () => {
expect(() => {
new Something();
}).toThrow();
});
it('should not throw if parameter is a Set', () => {
expect(() => {
new Something(new Set([1, 2]));
}).not.toThrow();
});
The Typescript compiler rightfully shown an error TS2554: Expected 1 arguments, but got 0
on the first test. Typescript编译器正确地显示了
error TS2554: Expected 1 arguments, but got 0
在第一次测试时error TS2554: Expected 1 arguments, but got 0
。
The only way I found to fix this issue is to change the constructor signature and declare my parameter as optional with type any
, but it doesn't feel right... 我找到修复此问题的唯一方法是更改构造函数签名并将我的参数声明为可选的类型为
any
,但它感觉不对...
export class Something {
private mySet: Set<string>;
constructor(aSet?: any) {
if (!(aSet instanceof Set)) {
throw new TypeError('Invalid parameter');
}
this.mySet = aSet;
}
}
Is it the proper approach or is there a better way to handle this? 这是正确的方法还是有更好的方法来处理这个问题?
Of course, the parameter shouldn't be made optional to make tests pass, this defies the purpose of strict typing. 当然,参数不应该是可选的,以使测试通过,这违背了严格键入的目的。
A function should be asserted with another type if it's not used like intended: 如果函数未按预期使用,则应使用其他类型声明该函数:
expect(() => {
new (<any>Something)();
}).toThrow();
Or, more specifically with construct signature that throws an error, ie returns never
: 或者,更具体地说,使用构造签名抛出错误,即
never
返回:
expect(() => {
new (<{ new(): never }>Something)();
}).toThrow();
Currently, I think that there are no appropriate approach for solving your problem, unless the TypeScript team have implemented disable compiler error for specific line. 目前,我认为没有合适的方法来解决您的问题,除非TypeScript团队已经为特定行实现了禁用编译器错误。 This feature is already mentioned here but it is still yet to come.
此功能已在此处提及,但尚未实现。
So by now, it's either you sacrifice type-safety or you should just ignore that error thrown by the compiler. 所以到现在为止,要么牺牲类型安全性,要么忽略编译器抛出的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.