Skip to content
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 .changeset/lemon-fans-scream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"lit-analyzer-fork": patch
---

Fix ifDefined logic to exclude null from the return type, instead of just undefined
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { HtmlNodeAttrAssignmentKind } from "../../../analyze/types/html-node/htm
import type { RuleModuleContext } from "../../../analyze/types/rule/rule-module-context.js";
import { lazy } from "../../../analyze/util/general-util.js";
import { removeUndefinedFromType } from "../type/remove-undefined-from-type.js";
import { isLitDirective } from "./is-lit-directive.js";
import { isLit1Directive, isLitDirective } from "./is-lit-directive.js";

export type BuiltInDirectiveKind =
| "ifDefined"
Expand Down Expand Up @@ -50,8 +50,14 @@ export function getDirective(assignment: HtmlNodeAttrAssignment, context: RuleMo
// This new type becomes the actual type of the expression
const actualType = lazy(() => {
if (args.length >= 1) {
const returnType = toSimpleType(checker.getTypeAtLocation(args[0]), checker);
return removeUndefinedFromType(returnType);
const exprType = toSimpleType(checker.getTypeAtLocation(assignment.expression), checker);

if (isLit1Directive(exprType)) {
const returnType = toSimpleType(checker.getTypeAtLocation(args[0]), checker);
return removeUndefinedFromType(returnType);
}

return toSimpleType(checker.getNonNullableType(checker.getTypeAtLocation(args[0])), checker);
}

return undefined;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ tsTest("Can assign 'null' in property binding", t => {
hasNoDiagnostics(t, diagnostics);
});

tsTest("Return type of `ifDefined` is not `null`", t => {
const { diagnostics } = getDiagnostics(`
const ifDefined = <T>(x: T) => x ?? "non-null";
html\`<input some-attribute="$\{ifDefined(Math.random() < 0.5 ? 123 : null)}" />\`;
`);
hasNoDiagnostics(t, diagnostics);
});

tsTest("Message for 'null' in attribute detects null type correctly", t => {
const { diagnostics } = getDiagnostics('html`<input maxlength="${{} as number | null}" />`');
hasDiagnostic(t, diagnostics, "no-nullable-attribute-binding");
Expand Down