Skip to content
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

Add supports for index type query and indexed access type #52

Merged
merged 1 commit into from
Dec 3, 2017

Conversation

mzp
Copy link
Contributor

@mzp mzp commented Dec 3, 2017

TypeScript 2.1 introduced index type query and indexed access type(i.e. keyof keyword). This pull request adds supports for it.

πŸ“ Example

TypeScript

interface Thing {
    name: string;
    width: number;
    height: number;
    inStock: boolean;
}

type K1 = keyof Thing;  // "name" | "width" | "height" | "inStock"
type K2 = keyof Thing[];  // "length" | "push" | "pop" | "concat" | ...
type K3 = keyof { [x: string]: Thing };  // string

type P1 = Thing["name"];  // string
type P2 = Thing["width" | "height"];  // number
type P3 = Thing["name" | "inStock"];  // string | boolean
type P4 = string["charAt"];  // (pos: number) => string
type P5 = string[]["push"];  // (...items: string[]) => number

Scala.js

object Keyof extends js.Object {
  type K1 = String
  type K2 = String
  type K3 = String
  type P1 = js.Any
  type P2 = js.Any
  type P3 = js.Any
  type P4 = js.Any
  type P5 = js.Any
}

✨ Convert strategy

Index Type Query

Index type querykeyof should be converted string literal type.
But it's converted to string type, because current Scala type system doesn't support literal type.

Indexed Access Type

Indexed access type should be converted to its member type.
But it is hard to traverse object member at Importer#typeToScala without symbol table.

I believe than inaccurate conversion is better than parse error, so I convert it to any type.

πŸŽ‰ Affects of this

keyof is widely used at TypeScript definitions. For example, 662 keyof exists in DefinitelyTyped.

$ git clone [email protected]:DefinitelyTyped/DefinitelyTyped.git
$ cd DefinitelyTyped
$ git grep keyof | wc -l
662

It mainly used to express types of object key.

at<T extends object>(
  object: T | null | undefined,
  ...props: Array<Many<keyof T>>
): Array<T[keyof T]>;

Copy link
Owner

@sjrd sjrd left a comment

Choose a reason for hiding this comment

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

Looks good, thanks :)

@sjrd sjrd merged commit a3b7c65 into sjrd:master Dec 3, 2017
@mzp mzp deleted the key-of branch December 4, 2017 09:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants