Skip to content

Resolution of Record-typed objects that extend string resolve to any #40892

Closed
@alecf

Description

@alecf

I'm using a style of nominal typing as described here: https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/

But I find when I have a object of type Record<NominalStringType, OtherType>, then resolving a key in that object always resolves to any
TypeScript Version: 4.0.3

Search Terms: Record Flavor Nominal String

Code

interface Flavoring<FlavorT> {
  _type?: FlavorT;
}
type FlavorString<FlavorT> = string & Flavoring<FlavorT>;
type MyString = FlavorString<'MyString'>;

// Create a record type using this nominal type
type RS<T extends string> = Record<T, number>;

// define an instance of this
const r: RS<MyString> = { foo: 1};

// `v` is typed as 'any' even though we know `Record<T, number>[K]` should be a number
const v = r['foo'];

// we can also try with an instance of the nominal type:
const foo: MyString = 'foo';

// `v2` still is type as `any`
const v2 = r[foo];

Expected behavior:

v and v2 above should be typed as a number

Actual behavior:

v and v2 are typed as any

Playground Link:

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGIBs4DcD2VQDmAPBtngCoB8yA3gFDLID6YAngA4QD8AXGprijkA3HQC+dNp35koAZTD4QxUoKrIAvMgDOiwsgBkMwYRICKlUVJQBZVgqUFNxvA9MByO2+XvLdOgD0AcgAwlAQcJDIcMjhCHgAJsjWyACu2vpgABbA2sggOAC2oHDoyRwQkhXIAEpyROTIEAAekCAJebqO1Fo1EPFQCQ0ANPmphQBG0H6BwQkQMKAocCDIoLorSMg4MMk52nTxILqxfHVEXnrKPbTIMDg4fACMYqKzyAAGWB9redZJcDy7hWrHcTSwEFW2RwqQIWWQAHcUABrAoIz59AZDcijEDjKZQSgAbQA0gBdH7aLIw9BJKbRMaTaCHHDHMDILDOKBE9z3HDuMlvIKIlAIFbRdDaHDJKCsRHAbLRVbrMCbFA7PYoArFEClcqcHgstl3B58S6OZy8h7uIXBL4AJkpYGA6DKuX1yzyHxBHyNJyw9q5RL5groQA

Related Issues:

This looks possibly related: #36981

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