Skip to content

Commit

Permalink
adding "__typename must be const" checks
Browse files Browse the repository at this point in the history
  • Loading branch information
Rash-Hit committed Mar 25, 2024
1 parent 66e8571 commit 6311463
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
16 changes: 16 additions & 0 deletions src/Errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,22 @@ export function typeNameInitializeNotString() {
return `Expected \`__typename\` property initializer to be a string literal. For example: \`__typename = "MyType"\` or \`__typename: "MyType";\`. ${TYPENAME_CONTEXT}`;
}

export function typeNameInitializeNotExpression() {
return `Expected \`__typename\` property initializer to be an expression with a const assertion. For example: \`__typename = "MyType" as const\`. ${TYPENAME_CONTEXT}`;
}

export function typeNameTypeNotReferenceNode() {
return `Expected \`__typename\` property type to be a TypeReferenceNode. ${TYPENAME_CONTEXT}`;
}

export function typeNameTypeNameNotIdentifier() {
return `Expected \`__typename\` property type name to be an Identifier. ${TYPENAME_CONTEXT}`;
}

export function typeNameTypeNameNotConst() {
return `Expected \`__typename\` property type name to be "const". ${TYPENAME_CONTEXT}`;
}

export function typeNameInitializerWrong(expected: string, actual: string) {
return `Expected \`__typename\` property initializer to be \`"${expected}"\`, found \`"${actual}"\`. ${TYPENAME_CONTEXT}`;
}
Expand Down
29 changes: 25 additions & 4 deletions src/Extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -740,18 +740,39 @@ class Extractor {
return false;
}

if (!ts.isStringLiteral(node.initializer)) {
this.report(node.initializer, E.typeNameInitializeNotString());
if (!ts.isAsExpression(node.initializer)) {
this.report(node.initializer, E.typeNameInitializeNotExpression())
return false;
}

if (node.initializer.text !== expectedName) {
if (!ts.isStringLiteral(node.initializer.expression)) {
this.report(node.initializer.expression, E.typeNameInitializeNotString());
return false
}

if (node.initializer.expression.text !== expectedName) {
this.report(
node.initializer,
E.typeNameInitializerWrong(expectedName, node.initializer.text),
E.typeNameInitializerWrong(expectedName, node.initializer.expression.text),
);
return false
}

if (!ts.isTypeReferenceNode(node.initializer.type)) {
this.report(node.initializer.type, E.typeNameTypeNotReferenceNode());
return false;
}

if (!ts.isIdentifier(node.initializer.type.typeName)) {
this.report(node.initializer.type.typeName, E.typeNameTypeNameNotIdentifier());
return false;
}

if (node.initializer.type.typeName.escapedText !== "const") {
this.report(node.initializer.type.typeName, E.typeNameTypeNameNotConst());
return false;
}

return true;
}

Expand Down

0 comments on commit 6311463

Please sign in to comment.