Skip to content

Keysof type operator #10425

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

Closed
wants to merge 5 commits into from
Closed
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
43 changes: 43 additions & 0 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2165,6 +2165,11 @@ namespace ts {
else if (type.flags & TypeFlags.NumberLiteral) {
writer.writeStringLiteral((<LiteralType>type).text);
}
else if (type.flags & TypeFlags.KeysQuery) {
writer.writeKeyword("keysof");
writeSpace(writer);
writeType((<KeysQueryType>type).baseType, flags);
}
else {
// Should never get here
// { ... }
Expand Down Expand Up @@ -5145,6 +5150,34 @@ namespace ts {
return links.resolvedType;
}

function resolveKeysQueryType(type: KeysQueryType): Type {
if (!type.resolvedBaseUnion) {
// Skip any essymbol members and remember to unescape the identifier before making a type from it
const memberTypes = map(filter(getPropertiesOfType(type.baseType),
symbol => !startsWith(symbol.name, "__@")),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you split this into intermediate variables?

symbol => getLiteralTypeForText(TypeFlags.StringLiteral, unescapeIdentifier(symbol.name))
);
type.resolvedBaseUnion = memberTypes ? getUnionType(memberTypes) : neverType;
}
return type.resolvedBaseUnion;
}

function getKeysQueryType(type: Type): KeysQueryType {
const queryType = createType(TypeFlags.KeysQuery) as KeysQueryType;
queryType.baseType = type;
return queryType;
}

function getTypeFromKeysQueryNode(node: KeysQueryNode): Type {
const links = getNodeLinks(node);
if (!links.resolvedType) {
// The expression is processed as an identifier expression, which we
// then store the resulting type of into a "KeysQuery" type
links.resolvedType = getKeysQueryType(getTypeFromTypeNode(node.type));
}
return links.resolvedType;
}

function getTypeOfGlobalSymbol(symbol: Symbol, arity: number): ObjectType {

function getTypeDeclaration(symbol: Symbol): Declaration {
Expand Down Expand Up @@ -5569,6 +5602,8 @@ namespace ts {
return getTypeFromTypeReference(<ExpressionWithTypeArguments>node);
case SyntaxKind.TypeQuery:
return getTypeFromTypeQueryNode(<TypeQueryNode>node);
case SyntaxKind.KeysQuery:
return getTypeFromKeysQueryNode(<KeysQueryNode>node);
case SyntaxKind.ArrayType:
case SyntaxKind.JSDocArrayType:
return getTypeFromArrayTypeNode(<ArrayTypeNode>node);
Expand Down Expand Up @@ -5855,6 +5890,9 @@ namespace ts {
if (type.flags & TypeFlags.Intersection) {
return getIntersectionType(instantiateList((<IntersectionType>type).types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes);
}
if (type.flags & TypeFlags.KeysQuery) {
return getKeysQueryType(instantiateType((<KeysQueryType>type).baseType, mapper));
}
}
return type;
}
Expand Down Expand Up @@ -6185,6 +6223,8 @@ namespace ts {
if (source.flags & (TypeFlags.Number | TypeFlags.NumberLiteral) && target.flags & TypeFlags.Enum) return true;
if (source.flags & TypeFlags.NumberLiteral && target.flags & TypeFlags.EnumLiteral && (<LiteralType>source).text === (<LiteralType>target).text) return true;
}
if (source.flags & TypeFlags.KeysQuery) return isTypeRelatedTo(resolveKeysQueryType(source as KeysQueryType), target, relation);
if (target.flags & TypeFlags.KeysQuery) return isTypeRelatedTo(source, resolveKeysQueryType(target as KeysQueryType), relation);
return false;
}

Expand Down Expand Up @@ -13356,6 +13396,9 @@ namespace ts {
}
contextualType = apparentType;
}
if (contextualType.flags & TypeFlags.KeysQuery) {
return type === stringType;
}
if (type.flags & TypeFlags.String) {
return maybeTypeOfKind(contextualType, TypeFlags.StringLiteral);
}
Expand Down
26 changes: 26 additions & 0 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ namespace ts {
visitNode(cbNode, (<TypePredicateNode>node).type);
case SyntaxKind.TypeQuery:
return visitNode(cbNode, (<TypeQueryNode>node).exprName);
case SyntaxKind.KeysQuery:
return visitNode(cbNode, (<KeysQueryNode>node).type);
case SyntaxKind.TypeLiteral:
return visitNodes(cbNodes, (<TypeLiteralNode>node).members);
case SyntaxKind.ArrayType:
Expand Down Expand Up @@ -2018,6 +2020,13 @@ namespace ts {
return finishNode(node);
}

function parseKeysQuery(): KeysQueryNode {
const node = <KeysQueryNode>createNode(SyntaxKind.KeysQuery);
parseExpected(SyntaxKind.KeysOfKeyword);
node.type = parseType();
return finishNode(node);
}

function parseTypeParameter(): TypeParameterDeclaration {
const node = <TypeParameterDeclaration>createNode(SyntaxKind.TypeParameter);
node.name = parseIdentifier();
Expand Down Expand Up @@ -2420,6 +2429,21 @@ namespace ts {
return nextToken() === SyntaxKind.NumericLiteral;
}

function nextTokenIsKeysQueryTypeTerminator() {
const next = nextToken();
switch (next) {
case SyntaxKind.DotToken:
case SyntaxKind.CommaToken:
case SyntaxKind.SemicolonToken:
case SyntaxKind.OpenBraceToken:
case SyntaxKind.CloseBraceToken:
case SyntaxKind.CloseParenToken:
case SyntaxKind.EqualsGreaterThanToken:
return true;
}
return false;
}

function parseNonArrayType(): TypeNode {
switch (token()) {
case SyntaxKind.AnyKeyword:
Expand Down Expand Up @@ -2453,6 +2477,8 @@ namespace ts {
}
case SyntaxKind.TypeOfKeyword:
return parseTypeQuery();
case SyntaxKind.KeysOfKeyword:
return lookAhead(nextTokenIsKeysQueryTypeTerminator) ? parseTypeReference() : parseKeysQuery();
case SyntaxKind.OpenBraceToken:
return parseTypeLiteral();
case SyntaxKind.OpenBracketToken:
Expand Down
1 change: 1 addition & 0 deletions src/compiler/scanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ namespace ts {
"async": SyntaxKind.AsyncKeyword,
"await": SyntaxKind.AwaitKeyword,
"of": SyntaxKind.OfKeyword,
"keysof": SyntaxKind.KeysOfKeyword,
"{": SyntaxKind.OpenBraceToken,
"}": SyntaxKind.CloseBraceToken,
"(": SyntaxKind.OpenParenToken,
Expand Down
35 changes: 26 additions & 9 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ namespace ts {
FromKeyword,
GlobalKeyword,
OfKeyword, // LastKeyword and LastToken
KeysOfKeyword,

// Parse tree nodes

Expand Down Expand Up @@ -207,6 +208,7 @@ namespace ts {
FunctionType,
ConstructorType,
TypeQuery,
KeysQuery,
TypeLiteral,
ArrayType,
TupleType,
Expand Down Expand Up @@ -766,6 +768,12 @@ namespace ts {
exprName: EntityName;
}

// @kind(SyntaxKind.KeysQuery)
export interface KeysQueryNode extends TypeNode {
" keys query brand ": never;
type: TypeNode;
}

// A TypeLiteral is the declaration node for an anonymous symbol.
// @kind(SyntaxKind.TypeLiteral)
export interface TypeLiteralNode extends TypeNode, Declaration {
Expand Down Expand Up @@ -2259,19 +2267,20 @@ namespace ts {
Union = 1 << 19, // Union (T | U)
Intersection = 1 << 20, // Intersection (T & U)
Anonymous = 1 << 21, // Anonymous
Instantiated = 1 << 22, // Instantiated anonymous type
KeysQuery = 1 << 22, // keysof <type expr> type
Instantiated = 1 << 23, // Instantiated anonymous type
/* @internal */
ObjectLiteral = 1 << 23, // Originates in an object literal
ObjectLiteral = 1 << 24, // Originates in an object literal
/* @internal */
FreshObjectLiteral = 1 << 24, // Fresh object literal type
FreshObjectLiteral = 1 << 25, // Fresh object literal type
/* @internal */
ContainsWideningType = 1 << 25, // Type is or contains undefined or null widening type
ContainsWideningType = 1 << 26, // Type is or contains undefined or null widening type
/* @internal */
ContainsObjectLiteral = 1 << 26, // Type is or contains object literal type
ContainsObjectLiteral = 1 << 27, // Type is or contains object literal type
/* @internal */
ContainsAnyFunctionType = 1 << 27, // Type is or contains object literal type
ThisType = 1 << 28, // This type
ObjectLiteralPatternWithComputedProperties = 1 << 29, // Object literal type implied by binding pattern has computed properties
ContainsAnyFunctionType = 1 << 28, // Type is or contains object literal type
ThisType = 1 << 29, // This type
ObjectLiteralPatternWithComputedProperties = 1 << 30, // Object literal type implied by binding pattern has computed properties

/* @internal */
Nullable = Undefined | Null,
Expand All @@ -2283,7 +2292,7 @@ namespace ts {
Intrinsic = Any | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never,
/* @internal */
Primitive = String | Number | Boolean | Enum | ESSymbol | Void | Undefined | Null | Literal,
StringLike = String | StringLiteral,
StringLike = String | StringLiteral | KeysQuery,
NumberLike = Number | NumberLiteral | Enum | EnumLiteral,
BooleanLike = Boolean | BooleanLiteral,
EnumLike = Enum | EnumLiteral,
Expand Down Expand Up @@ -2338,6 +2347,14 @@ namespace ts {
// Object types (TypeFlags.ObjectType)
export interface ObjectType extends Type { }

// KeysOf Query types (TypeFlags.KeysQuery)
export interface KeysQueryType extends Type {
baseType: Type;
/* @internal */
// Do not access directly. Use resolveKeysQueryType.
resolvedBaseUnion?: Type;
}

// Class and interface types (TypeFlags.Class and TypeFlags.Interface)
export interface InterfaceType extends ObjectType {
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
Expand Down
2 changes: 1 addition & 1 deletion src/services/formatting/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ namespace ts.formatting {

this.NoSpaceBeforeComma = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CommaToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));

this.SpaceAfterCertainKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.VarKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.NewKeyword, SyntaxKind.DeleteKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.TypeOfKeyword, SyntaxKind.AwaitKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.SpaceAfterCertainKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.VarKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.NewKeyword, SyntaxKind.DeleteKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.TypeOfKeyword, SyntaxKind.KeysOfKeyword, SyntaxKind.AwaitKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.SpaceAfterLetConstInVariableDeclaration = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.LetKeyword, SyntaxKind.ConstKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), RuleAction.Space));
this.NoSpaceBeforeOpenParenInFuncCall = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), RuleAction.Delete));
this.SpaceAfterFunctionInFuncDecl = new Rule(RuleDescriptor.create3(SyntaxKind.FunctionKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext), RuleAction.Space));
Expand Down
73 changes: 73 additions & 0 deletions tests/baselines/reference/simpleKeysofTest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
//// [simpleKeysofTest.ts]
// First, check that the new keyword doesn't interfere
// with any other potential uses of the identifier `keysof`.
namespace keysof {
export type name = {};
}
function old(a: keysof.name) {}

type keysof = {a: string};
function old2(a: keysof, b: keysof): keysof { return {a: ""}; }
var old3 = (): keysof => ({a: ""});

function disambiguate1(a: keysof ({b: number})) {}
function disambiguate2(): keysof ({a}) {return "a";}

// Then check that the `keysof` operator works as expected
interface FooBar {
foo: "yes";
bar: "no";
[index: string]: string; // Remove when the indexer is patched to passthru unions
}

function pick(thing: FooBar, member: keysof FooBar) {
return thing[member];
}

const a = pick({foo: "yes", "bar": "no"}, "bar");

function pick2<T>(thing: T, member: keysof T): keysof T {
return member;
}
const realA: "a" = "a";
const x = pick2({a: "", b: 0}, realA);
const xx = pick2({a: "", b: 0}, "a");
const item = {0: "yes", 1: "no"};
const xxx = pick2(item, "0");

function annotate<U, T extends keysof U>(obj: U, key: T): U & {annotation: T} {
const ret = obj as U & {annotation: T};
if (key === "annotation") return ret; // Already annotated
ret.annotation = key;
return ret;
}

annotate({a: "things", b: "stuff"}, "b").annotation === "b";


//// [simpleKeysofTest.js]
function old(a) { }
function old2(a, b) { return { a: "" }; }
var old3 = function () { return ({ a: "" }); };
function disambiguate1(a) { }
function disambiguate2() { return "a"; }
function pick(thing, member) {
return thing[member];
}
var a = pick({ foo: "yes", "bar": "no" }, "bar");
function pick2(thing, member) {
return member;
}
var realA = "a";
var x = pick2({ a: "", b: 0 }, realA);
var xx = pick2({ a: "", b: 0 }, "a");
var item = { 0: "yes", 1: "no" };
var xxx = pick2(item, "0");
function annotate(obj, key) {
var ret = obj;
if (key === "annotation")
return ret; // Already annotated
ret.annotation = key;
return ret;
}
annotate({ a: "things", b: "stuff" }, "b").annotation === "b";
Loading