Skip to content

Support a fieldof type. #4822

Closed
Closed
@Fruneau

Description

@Fruneau

In some cases, we may want to have a function that read one field of an object identified by a parameter. Here is a small synthetic use case, for the purpose of the discussion:

interface Help {
    brief: string;
    detailed: string;
    contextual: string;
}

function getHelpString(help: Help, format: string): string
{
    return help[format];
}

In that particular case, the type checker cannot ensure that we are doing things right. In order to make the type checker happy, we need a way to tell it that format is actually part of an implicit enumeration that only contains the names of the fields of the interface Help. This could be done by introducing a new type inference operator, for example fieldof.

function getHelpString(help: Help, format: fieldof Help): string
{
    return help[format];
}

This may not look like a very common use case, but I hoped to have such an operator in order to port incrementally a large amount of javascript code to typescript.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions