Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jestjs - TypeScript Jest Matchers functions are typed any

Jest doesn't type some of its expect functions in Matchers. For example, it doesn't generate compiling errors for following code:

expect('123').toEqual(123);
expect(() => '123').toHaveReturnedWith(123);

Here is how toEqual and toHaveReturnedWith are declared:

toEqual<E = any>(expected: E): R;
toHaveReturnedWith<E = any>(expected: E): R;

Obviously, parameters of both are typed any. Even though it allows you to specify a type, it is not bound with the actual value. They can be improved like this:

interface Matchers<R, T = {}> {
   toEqual(expected: T): R;
   toHaveReturnedWith(expected: ReturnType<T>): R;
}

Now TypeScript complains:

expect('123').toEqual(123); // type number is not assignable to type string
expect(() => '123').toHaveReturnedWith(123); // type number is not assignable to type

My question is why jest chooses not to type them like above which is obviously better?

  • Jest doesn't really care about type safety since those are unit tests and won't pass any way?
  • Backward compatible?
  • etc.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...