typescript - 如何在 Typescript 中使用 Chai expect() 验证特定

我曾尝试在以前的帖子中寻找答案,但我没有找到答案,所以这里是:

我目前正在尝试使用 Typescript 中 Chai 的 expect() 来测试对象实例属性值的返回类型。到目前为止,我试过这个:

/* My type file */

export type customType = "one" | "two" | "three";
export default customType;

/* My test file */

import customType from '{path_to_customType}'; // 'customType' is declared but its value is never read.

const newObject = new Object({property1: value1}) //note: value1 is of type customType

describe("Class1 test", () => {
    it('my tests', () => {
        expect(newObject).to.have.property("property1").to.equal("value1"); //so far, this one works fine
        expect(newObject).to.be.a('customType'); // not working
        expect(newObject).to.be.an('customType'); // not working
        expect(newObject).to.be.a(customType); // not working
        expect(newObject).to.be.an(customType); // not working
        expect(typeof newObject.getProperty1()).to.equal('customType'); // not working
        expect(newObject).to.be.an.instanceof(customType); // not working
        expect(newObject).to.be.an.instanceof('customType'); // not working
        assert.typeOf(newObject.getProperty1(), 'customType'); // not working
        assert.typeOf(newObject.getProperty1(), customType); // not working
    });
});

如您所见,value1 应该是 customType 类型,但它给了我一个错误,因为从未读取过 customType。 如何验证我的值是否属于特定的自定义类型?

**注意:在我的对象定义中,属性 property1 指定为类型 customType

*UPDATE 我刚刚注意到 value1 的返回类型是“string”,就好像该类型只是一个别名...那么我该如何测试呢?

最佳答案

TypeScript 的类型系统纯粹是一个编译时特性。运行代码没有类型。您可以使用typeof 来测试值是否为boolean、number、string、object 等,您还可以测试一个Object 是否是一个类的实例。

但是,您的 customType 根本不是可以在运行时检查的东西。一旦代码被转换为 JavaScript 以便运行,customType 就像任何其他字符串一样只是一个字符串。

关于typescript - 如何在 Typescript 中使用 Chai expect() 验证特定类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70842333/

相关文章:

pine-script - 如何在版本 5 中使用多个指标 ()

npm - sh : hardhat: command not found when install

java - 如何对 Map> 进行排序?

postgresql - GROUP BY 时前两个值的差异

julia - JuMP 非线性优化约束被打破到 O(1e-9)

react-native - 如何在 React Navigation 中使用图标代替原来的后退按钮

python - 如何使用 pybind11 从 C++ 调用 python 函数?

flutter - 如何修复此语法错误?不可为 null 的实例字段 'students' 必须初始

python - 有没有办法用mypy覆盖python中继承的类属性类型?

python - 将列名传递给 Pandas read_csv() 函数