Skip to content

Statically guarantee presence of object key via string literal type #33410

Closed
@rix0rrr

Description

@rix0rrr

Search Terms

object key string literal

Suggestion

I'm trying to write a function to set a field in an object using a string literal type. I can write the signature for it, but I can't write the body. A simplified version of it looks like this:

function foo1<N extends string>(key: N): {[key in N]: string} {
    return { [key]: 'foo' };
//  ~~~~~~~~~~~~~~~~~~~~~~~~
//  Type '{ [x: string]: string }' is not assignable to type '{[key in N: string}'
}


function foo2<N extends string>(key: N): {[key in N]: string} {
    return { [key]: 'foo' } as any; // Cast away the error
}


const x = foo2('henk');   // x :: { henk: string } as expected

I imagine this has something to do with the keys of an object literal being declared to be string and the stronger type N extends string getting dropped on the floor?

But the code feels like it is correct and it feels like the type system should be able to see that.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

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