From 4cc6d91a92adc1fc6b14d5de703803ec5688a84a Mon Sep 17 00:00:00 2001 From: Russell Bicknell Date: Wed, 11 Jan 2023 14:38:23 -0800 Subject: [PATCH 1/2] The `ifDefined` directive should return a non-null type. --- .../src/test/rules/no-nullable-attribute-binding.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/lit-analyzer/src/test/rules/no-nullable-attribute-binding.ts b/packages/lit-analyzer/src/test/rules/no-nullable-attribute-binding.ts index 3e788653..001e57bc 100644 --- a/packages/lit-analyzer/src/test/rules/no-nullable-attribute-binding.ts +++ b/packages/lit-analyzer/src/test/rules/no-nullable-attribute-binding.ts @@ -25,3 +25,11 @@ tsTest("Can assign 'null' in property binding", t => { const { diagnostics } = getDiagnostics('html``'); hasNoDiagnostics(t, diagnostics); }); + +tsTest("Return type of `ifDefined` is not `null`", t => { + const { diagnostics } = getDiagnostics(` + const ifDefined = (x: T) => x ?? "non-null"; + html\`\`; + `); + hasNoDiagnostics(t, diagnostics); +}); From 942db2937d4f525dcc6fc61ff7c2398c444d5dc9 Mon Sep 17 00:00:00 2001 From: Russell Bicknell Date: Wed, 11 Jan 2023 16:28:18 -0800 Subject: [PATCH 2/2] `ifDefined` in Lit 2 also drops `null`. --- .../src/lib/rules/util/directive/get-directive.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/lit-analyzer/src/lib/rules/util/directive/get-directive.ts b/packages/lit-analyzer/src/lib/rules/util/directive/get-directive.ts index 3226a2b1..5d05faaf 100644 --- a/packages/lit-analyzer/src/lib/rules/util/directive/get-directive.ts +++ b/packages/lit-analyzer/src/lib/rules/util/directive/get-directive.ts @@ -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" @@ -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;