Thanks to visit codestin.com
Credit goes to github.com

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/tame-wombats-share.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@lit-labs/tsserver-plugin': patch
---

Add getLitExpressionType to get the effective type of a binding expression
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import type * as ts from 'typescript';

/**
* Given a type of a binding expression, return the type that we should
* type check against.
*
* This is usually the same as just returning the type, however, lit-html's
* rendering behavior does have a few special values.
*
* The `noChange` and `nothing` symbols are always allowed in any binding.
*
* DirectiveResults should be type checked as the return type of the `render`
* method on the directive class.
*
* TODO: Move into the analyzer.
*/
export function getLitExpressionType(
type: ts.Type,
typescript: typeof ts,
program: ts.Program
): ts.Type {
const checker: ExtendedTypeChecker = program.getTypeChecker();
const specialType = isSpecialValue(type, typescript);
// nothing and noChange are assignable to anything in a binding.
if (specialType === SpecialValuesEnum.SentinelSymbol) {
return checker.getAnyType();
}
// Unwrap a DirectiveResult to get the type it renders as.
if (specialType === SpecialValuesEnum.DirectiveResult) {
const directiveResultType = getRenderTypeFromDirectiveResult(
type,
typescript,
checker
);
return directiveResultType ?? type;
}
// If our checker can't create new unions, we can't do anything more.
if (checker.getUnionType == null) {
return type;
}
// Apply the same transform through a union.
if (type.isUnion()) {
// Check if any of the types are special. If not, we can early exit.
let hasSpecial = false;
for (const subtype of type.types) {
const subtypeSpecial = isSpecialValue(subtype, typescript);
if (subtypeSpecial !== SpecialValuesEnum.NormalType) {
hasSpecial = true;
break;
}
}
if (!hasSpecial) {
return type;
}
// Apply the same transform to each subtype.
const newSubtypes = type.types.map((subtype) =>
getLitExpressionType(subtype, typescript, program)
);
return checker.getUnionType(newSubtypes);
}
return type;
}

interface ExtendedTypeChecker extends ts.TypeChecker {
getUnionType?(types: Array<ts.Type>): ts.Type;
}

function isTypeReference(
type: ts.Type,
typescript: typeof ts
): type is ts.TypeReference {
return (
(type.flags & typescript.TypeFlags.Object) !== 0 &&
!!(type as ts.TypeReference).target
);
}

function getRenderTypeFromDirectiveResult(
type: ts.Type,
typescript: typeof ts,
checker: ExtendedTypeChecker
): ts.Type | undefined {
if (!isTypeReference(type, typescript)) {
return undefined;
}
// So, we have a DirectiveResult<{new (...): ActualDirective}
// and we want to get ReturnType<ActualDirective['render']>
const constructorTypes = checker.getTypeArguments(type);
if (!constructorTypes || constructorTypes.length === 0) {
return undefined;
}
const finalTypes = [];
for (const constructorType of constructorTypes) {
const constructSignatures = constructorType.getConstructSignatures();
for (const signature of constructSignatures) {
const actualDirectiveType = checker.getReturnTypeOfSignature(signature);
if (actualDirectiveType == null) {
continue;
}
const renderMethod = actualDirectiveType.getProperty('render');
if (renderMethod == null) {
continue;
}
const renderType = checker.getTypeOfSymbol(renderMethod);
const callSignatures = renderType.getCallSignatures();
for (const callSignature of callSignatures) {
finalTypes.push(callSignature.getReturnType());
}
}
}
if (finalTypes.length === 0) {
return undefined;
}
if (finalTypes.length === 1) {
return finalTypes[0];
}
if (checker.getUnionType != null) {
// Return a union of the types if we can.
return checker.getUnionType(finalTypes);
}
return finalTypes[0];
}

const SpecialValuesEnum = {
NormalType: 0 as const,
SentinelSymbol: 1 as const,
DirectiveResult: 2 as const,
};
type SpecialValuesEnum =
(typeof SpecialValuesEnum)[keyof typeof SpecialValuesEnum];

function isSpecialValue(
type: ts.Type,
typescript: typeof ts
): SpecialValuesEnum {
const escapedName = type.symbol?.getEscapedName();
if (
escapedName !== 'noChange' &&
escapedName !== 'nothing' &&
escapedName !== 'DirectiveResult'
) {
return SpecialValuesEnum.NormalType;
}
// Is it declared inside of lit-html?
const declarations = type.symbol.declarations;
if (declarations) {
let isInsideLitHtml = false;
for (const decl of declarations) {
const sourceFile = decl.getSourceFile();
if (sourceFile.fileName.includes('lit-html')) {
isInsideLitHtml = true;
break;
}
}
if (isInsideLitHtml === false) {
return SpecialValuesEnum.NormalType;
}
}
if (escapedName === 'DirectiveResult') {
return SpecialValuesEnum.DirectiveResult;
}
// Is it a unique symbol?
if (type.flags & typescript.TypeFlags.UniqueESSymbol) {
return SpecialValuesEnum.SentinelSymbol;
}
return SpecialValuesEnum.NormalType;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Test-only fake lit-html type declarations used to exercise
* `getLitExpressionType` logic without depending on the real lit-html.
*
* The filename intentionally contains `lit-html` so that the helper's
* `isSpecialValue` logic (which checks the source file path) treats these
* exports as coming from lit-html.
*/

// Sentinel unique symbols (mimic lit-html exports). Using simple Symbol() so
// the declared type is a distinct unique symbol.
export const noChange = Symbol('noChange');
export const nothing = Symbol('nothing');

// Minimal DirectiveResult generic. Only the generic parameter (a constructor)
// is used by the code under test; the shape is irrelevant.
export interface DirectiveResult<
C extends abstract new (...args: unknown[]) => unknown,
> {
/** brand */ readonly __brand?: 'DirectiveResult';
// Reference the generic so it is not flagged as unused.
readonly __c?: C;
}

// Two fake directive classes with different render return types so we can
// verify unwrapping (including union return types).
export class MyDirective {
render(): number {
return 42;
}
}

export class OtherDirective {
render(): string | boolean {
return '';
}
}

// Export some typed values (the actual runtime values are not important;
// we just need the static types for the TypeScript type checker).
export const directiveResultNumber = {} as unknown as DirectiveResult<
typeof MyDirective
>;
export const directiveResultUnion = {} as unknown as DirectiveResult<
typeof OtherDirective
>;
export const directiveResultOrString = {} as unknown as
| DirectiveResult<typeof MyDirective>
| string;
export const sentinelOnly = noChange;
export const sentinelUnion: typeof noChange | number = noChange;
export const nothingValue = nothing;
export const nothingUnion: typeof nothing | string = nothing;

// Plain non-special exports for negative test cases.
export const plainNumber = 123;
export const plainUnion: number | string = 0 as unknown as number | string;
Loading
Loading