Skip to content

Commit

Permalink
fix(type): correctly check X extends Date and print validation erro…
Browse files Browse the repository at this point in the history
…rs with caused value.

Previously `{x: string} extends Date` returned true which is wrong.
  • Loading branch information
marcj committed Oct 23, 2023
1 parent 25da2d0 commit fde795e
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/type/src/reflection/extends.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,12 @@ export function isExtendable(leftValue: AssignableType, rightValue: AssignableTy
return true;
}

if ((left.kind === ReflectionKind.class || left.kind === ReflectionKind.objectLiteral) && (right.kind === ReflectionKind.class && right.classType === Date)) {
if (left.kind === ReflectionKind.objectLiteral && left.types.length === 0) return true;
if (left.kind === ReflectionKind.class && left.classType === Date) return true;
return false;
}

if ((left.kind === ReflectionKind.class || left.kind === ReflectionKind.objectLiteral) && (right.kind === ReflectionKind.objectLiteral || right.kind === ReflectionKind.class)) {
const rightConstructor = (right.types as Type[]).find(v => (v.kind === ReflectionKind.methodSignature && v.name === 'new')) as TypeMethodSignature | undefined;

Expand Down
2 changes: 1 addition & 1 deletion packages/type/src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export class ValidationErrorItem {
messagedCausedBy = ` caused by value ${serialisedValue}`;
}

return `${(prefix ? prefix + '.' : '') + this.path}(${this.code}): ${this.message}`;
return `${(prefix ? prefix + '.' : '') + this.path}(${this.code}): ${this.message}${messagedCausedBy}`;
}
}

Expand Down
5 changes: 5 additions & 0 deletions packages/type/tests/type.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,11 @@ test('interface with method', () => {
validExtend<Connection, { id: number, write(data: SubUint16Array): void }>();
});

test('extends Date', () => {
validExtend<{}, Date>();
invalidExtend<{y: string}, Date>();
});

test('readonly constructor properties', () => {
class Pilot {
constructor(readonly name: string, readonly age: number) {
Expand Down

0 comments on commit fde795e

Please sign in to comment.