Introduce Extends
See original GitHub issueHi Joseph,
there is the use-case of testing if only certain TS types cover a special type definition.
// a type that reflects functions and arrow functions
type Fn<A extends any[] = any[], R = any> = (...args: A) => R;
I need to ensure that only and only function cover the Fn
type. E.g. type Fn = any
would cover functions but also other types that are not intended to be expected. The existing type Equals
is unsuitable for testing if types are inside or outside of a domain (read: a set of valid types).
Introducing an Extends
type to tsafe would make it possible to assert that Fn
covers the types we intend to cover and to ensure that other types are not covered (as expected).
👇👇👇
type Extends<T1, T2> = T1 extends T2 ? true : false;
By having the following unit tests, we would ensure that the Fn
type does not cover more types than expected.
describe('type Fn', () => {
function fn() {}
class A {}
// "sunny path": these would sill succeed if `type Fn = any`
it('should cover () => any', () => { tsafeAssert<Extends<() => any, Fn>>(); });
it('should cover () => void', () => { tsafeAssert<Extends<() => void, Fn>>(); });
it('should cover (...args: any[]) => any', () => { tsafeAssert<Extends<(...args: any[]) => any, Fn>>(); });
it('should cover typeof fn', () => { tsafeAssert<Extends<typeof fn, Fn>>(); });
// "correctness": these would fail if `type Fn = any`
it('should not cover undefined', () => { tsafeAssert<Not<Extends<undefined, Fn>>>(); });
it('should not cover null', () => { tsafeAssert<Not<Extends<null, Fn>>>(); });
it('should not cover boolean', () => { tsafeAssert<Not<Extends<boolean, Fn>>>(); });
it('should not cover number', () => { tsafeAssert<Not<Extends<number, Fn>>>(); });
it('should not cover string', () => { tsafeAssert<Not<Extends<string, Fn>>>(); });
it('should not cover array', () => { tsafeAssert<Not<Extends<any[], Fn>>>(); });
it('should not cover object', () => { tsafeAssert<Not<Extends<object, Fn>>>(); });
it('should not cover class', () => { tsafeAssert<Not<Extends<A, Fn>>>(); });
});
If you also think that Extends
would be a great fit for tsafe, I would be happy to create a PR!
What do you think?
Thanks!
Issue Analytics
- State:
- Created a year ago
- Comments:11 (11 by maintainers)
Top GitHub Comments
Verny nice! Thank you 😃
BTW, i’m using extends already, in https://github.com/codegouvfr/react-dsfr