Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { HtmlNodeAttrAssignment, HtmlNodeAttrAssignmentKind } from "../../../ana
import { 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 @@ -48,8 +48,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 @@ -25,3 +25,11 @@ tsTest("Can assign 'null' in property binding", t => {
const { diagnostics } = getDiagnostics('html`<input .selectionEnd="${{} as number | null}" />`');
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);
});