I was in situation where I needed to write Jest expectation for an object and I already have the description of this object in my Typescript definitions. My initial question was Why I can’t just ask Jest if this object is from this interface?

test('request returns list of database instances', async () => {

const result = await getDB()

expect(result).is('DBInstance[]')

})

Simple question with simple solution- writing some code.

So, the code is written(selfrefactor/is) and is usable like so:

Install with yarn add https://github.com/selfrefactor/is#0.5.0

Initialize the library with the location of your typings

const {is} = require('is')

is('init', 'YOUR_FULL_PATH_TO/typings.d.ts')

Afterward you are free to do so:

const isValid = is(1, 'number') // => true const isValidSecond = is([1,2], 'number[]') // => true const isValidThird = is({foo: 1, bar: 'baz'}, 'Foo') // => true

// `Foo` is interface `{foo: number, bar: string}`

You can also extend Jest's expect object:

const isLib = require('is')

isLib.is('init', 'YOUR_FULL_PATH_TO/typings.d.ts')



expect.extend({

is(received, argument) {

const pass = isLib.is(received, argument);

if (pass) {

return {

message: () => `expected ${received} to have typing '${argument}'`,

pass: true,

};

} else {

return {

message: () =>

`expected ${received} to not have typing '${argument}'`,

pass: false,

}

}

}

})

Optional interface properties

In Typescript, we have optional interface properties:

interface Foo{ foo: number

bar?: string }

And now the question is ‘Do you respect those properties or do you skip them?’

Actually, we have to do both.

So once the library is initialized, two sets of interfaces are loaded:

Where all optional properties are skipped Where all optional properties are considered as strict properties

When we are using is({foo: 1}, 'Foo'}) , then option 1 is used. In order to access option 2 , we have to use method isx :

isx({foo:1, bar: 'baz'}, 'Foo') // => true

Using the library on the client

Currently the library can be used only in Node.js or Jest context.

In order to be available for the client, there should be an option to load typings from a plain string, not only from a filepath.

This option is not yet available, but it might land in the future versions of this library.

I share once again the repo link: https://github.com/selfrefactor/is