Skip to content

Feature Request: Allow typeof with index types #22194

Closed
@SLaks

Description

@SLaks

Revised feature request: Please allow typeof in mapped types:

Given a type like this:

type Enum<TEnum> = {
    [TName in keyof typeof TEnum]: TEnum[TName]
}

I want to write

type Schema<TObject> = {
    [TName in keyof TObject]: Enum<typeof (TObject[TName])>
}

This way, given the property declared as foo: SomeEnum, the mapped type would produce foo: Enum<typeof SomeEnum>, which would then match actual property foo: SomeEnum.

TObject[TName] is a value, so typeof should apply. However, this currently gives a syntax error.
Removing the parentheses complains (correctly) that TObject itself is a type, not a value.


TypeScript Version: 2.7.0

Search Terms: typeof keyof generic

Playground Link:
Minimal: http://www.typescriptlang.org/play/index.html#src=enum%20Color%20%7B%0D%0A%20%20%20%20Red%2C%20Green%2C%20Blue%0D%0A%7D%0D%0A%0D%0Atype%20Enum%3CTEnum%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BTName%20in%20keyof%20TEnum%5D%3A%20TEnum%5BTName%5D%3B%0D%0A%7D%0D%0A%0D%0Ainterface%20MyClass%20%7B%0D%0A%20%20%20%20color%3A%20Color%3B%0D%0A%7D%0D%0A%0D%0Aconst%20test%3A%20Enum%3Ctypeof%20(MyClass%5B'name'%5D)%20%3E%20%3D%20Color%3B%0D%0A

With motivating real-world example:
http://www.typescriptlang.org/play/index.html#src=enum%20Color%20%7B%0D%0A%20%20%20%20Red%2C%20Green%2C%20Blue%0D%0A%7D%0D%0A%0D%0Aenum%20Shape%20%7B%0D%0A%20%20%20%20Square%2C%20Circle%2C%20Triangle%0D%0A%7D%0D%0A%0D%0Atype%20Enum%3CTEnum%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BTName%20in%20keyof%20TEnum%5D%3A%20TEnum%5BTName%5D%3B%0D%0A%7D%3B%0D%0A%0D%0A%2F%2F%20Simple%20sample%3A%0D%0Aconst%20test%3A%20Enum%3Ctypeof%20Shape%3E%20%3D%20Shape%3B%0D%0A%0D%0A%2F%2F%20Real-world%20sample%20usage%3A%0D%0Ainterface%20MyClass%20%7B%0D%0A%20%20%20%20name%3A%20Date%3B%0D%0A%20%20%20%20color%3A%20Color%3B%0D%0A%20%20%20%20shape%3A%20Shape%3B%0D%0A%7D%0D%0Atype%20Schema%3CT%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BTName%20in%20keyof%20T%5D%3A%20(%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20For%20classes%3A%0D%0A%20%20%20%20%20%20%20%20%7B%20new()%3A%20T%5BTName%5D%20%7D%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20For%20enums%3A%0D%0A%20%20%20%20%20%20%20%20%7CEnum%3CT%5BTName%5D%3E%0D%0A%20%20%20%20)%0D%0A%7D%0D%0A%0D%0Aconst%20myClassSchema%3A%20Schema%3CMyClass%3E%20%3D%20%7B%0D%0A%20%20%20%20name%3A%20Date%2C%0D%0A%20%20%20%20color%3A%20Color%2C%0D%0A%20%20%20%20shape%3A%20Shape%2C%0D%0A%7D%3B

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions