首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >强类型深度相等断言与TypeScript和Chai

强类型深度相等断言与TypeScript和Chai
EN

Stack Overflow用户
提问于 2019-01-15 21:27:28
回答 1查看 2K关注 0票数 3

我有一个TypeScript函数,它返回Foo类型

代码语言:javascript
复制
interface Foo {
  bar: string;
  baz: string;
}

function getFoo(): Foo {
  return {
    bar: 'hello',
    baz: 'world',
  };
}

// Chai Assertion
it('Should return a Foo', () => {
  expect(getFoo()).to.deep.equal({
    bar: 'hello',
    baz: 'world',
  });
})

当我更改Foo接口时,getFoo()函数会产生一个TypeScript错误:

代码语言:javascript
复制
interface Foo {
  bar: number;  // change these to numbers instead
  baz: number;
}

function getFoo(): Foo {
  // Compile time error! Numbers aren't strings!
  return {
    bar: 'hello',
    baz: 'world',
  };
}

但是,我的Mocha测试不会触发编译时错误!

有一种类型安全的方法来做expect().to.deep.equal()吗?类似于:

代码语言:javascript
复制
// Strawman for how I'd like to do type-safety for deep equality assertions,
// though this generic signature still seems unnecessary?
expect<Foo>(getFoo()).to.deep.equal({
  bar: 'hello',
  baz: 'world',
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-15 23:16:26

是否有一种类型安全的方法来执行expect().to.deep.equal()

不是在equal的类型定义中,因为它是为运行时检查而设计的,因此有意使用any

无论在外部做得多么容易:

代码语言:javascript
复制
const expected: Foo = {
  bar: 'hello',
  baz: 'world',
};
expect(getFoo()).to.deep.equal(expected);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54207065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档