Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(type): intersection of two different primitives #549

Merged
merged 2 commits into from
Feb 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/type/src/reflection/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1400,6 +1400,11 @@ export class Processor {
return isExtendable(a, b) ? a : { kind: ReflectionKind.never };
}

// two different primitives always return never
if (isPrimitive(a) && isPrimitive(b) && a.kind !== b.kind) {
return { kind: ReflectionKind.never }
}

if (a.kind === ReflectionKind.objectLiteral || a.kind === ReflectionKind.class || a.kind === ReflectionKind.never || a.kind === ReflectionKind.unknown) return b;

if (b.annotations) {
Expand Down
16 changes: 16 additions & 0 deletions packages/type/tests/type.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ test('intersection same type', () => {
expect(stringifyType(typeOf<Username & string>())).toBe('Username');
});


test('intersection different primitive types', () => {
// just testing a few cases as there would be quite a few combinations
expect(stringifyType(typeOf<string & number>())).toBe('never');
expect(stringifyType(typeOf<undefined & null>())).toBe('never');
expect(stringifyType(typeOf<boolean & null>())).toBe('never');
expect(stringifyType(typeOf<bigint & number>())).toBe('never');
expect(stringifyType(typeOf<3 & 6>())).toBe('never');
});

test('intersection with never', () => {
type A = never & Group<'a'>;
type B = Group<'b'> & never;
Expand Down Expand Up @@ -146,6 +156,12 @@ test('intersection simply overrides properties', () => {
const password = findMember('password', type.types);
assertType(password, ReflectionKind.propertySignature);
assertType(password.type, ReflectionKind.void);

type t1 = User & { readonly password?: string };
const type1 = typeOf<t1>() as TypeObjectLiteral;
const password1 = findMember('password', type1.types) as TypeProperty;
expect(password1.optional).toBe(true);
expect(password1.readonly).toBe(true);
});

test('copy index access', () => {
Expand Down
Loading