如何在 Typescript 中使用 Chai Expect() 验证特定类型?

mat*_*rai 5 types mocha.js chai typescript typescript-generics

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

我目前正在尝试使用 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
    });
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

ksh*_*ine 3

TypeScript 的类型系统纯粹是编译时功能。运行代码没有类型。您可以用来typeof测试值是否为布尔值、数字、字符串、对象等,还可以测试对象是否是类的实例。

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