-
Notifications
You must be signed in to change notification settings - Fork 1k
Add func to get the effective type of a binding expression #5052
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6547183
Initial implementation of getLitExpressionType
rictic df8ded7
Add tests for getLitExpressionType.
rictic 11f2065
Also test type strings
rictic ff75ec2
Changeset
rictic 287892b
Prettier.
rictic 76909a6
Add todo.
rictic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
167 changes: 167 additions & 0 deletions
167
packages/labs/tsserver-plugin/src/lib/type-helpers/lit-expression-type.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
57 changes: 57 additions & 0 deletions
57
packages/labs/tsserver-plugin/src/test/lib/fake-lit-html-types.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.