microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.26k stars 12.52k forks source link

Create an object, the value of the enumeration is used as the key of the object, the object point value is a literal type, but typescript does not generate an exact type for the object #49722

Closed declanchiu closed 2 years ago

declanchiu commented 2 years ago

Bug Report

🔎 Search Terms

typecript does not automatically generate the correct type、enum、Object key in enum

🕗 Version & Regression Information

⏯ Playground Link

Playground link with relevant code

💻 Code

export enum OpenApiVersion {
  'openapi2' = 'openapi2',
  'openapi30' = 'openapi30',
  'openapi31' = 'openapi31',
}

export const OpenApiVersionExportName = {
  [OpenApiVersion.openapi31]: 'openapi',
  [OpenApiVersion.openapi30]: 'openapi',
  [OpenApiVersion.openapi2]: 'swagger',
};

🙁 Actual behavior

Typescript Generated Types 👇

const OpenApiVersionExportName: {
    openapi31: string;
    openapi30: string;
    openapi2: string;
}

🙂 Expected behavior

This is my expectation 👇

const OpenApiVersionExportName: {
    openapi31: 'openapi';
    openapi30: 'openapi';
    openapi2: 'swagger';
}
RyanCavanaugh commented 2 years ago

This didn't change between 4.3 and 4.7 as far as I can tell. The current behavior is the expected behavior; if you want the "expected" behavior use as const either on the strings themselves or the entire object

export const OpenApiVersionExportName = {
  [OpenApiVersion.openapi31]: 'openapi',
  [OpenApiVersion.openapi30]: 'openapi',
  [OpenApiVersion.openapi2]: 'swagger',
} as const
declanchiu commented 2 years ago

我这如果真的,你是在和 4.3.7 之间变化。当前行为是没有行为;“潜在”行为as const,在字符串本身就是对象上使用

export const OpenApiVersionExportName = {
  [OpenApiVersion.openapi31]: 'openapi',
  [OpenApiVersion.openapi30]: 'openapi',
  [OpenApiVersion.openapi2]: 'swagger',
} as const

oh !! I am very sorry for wasting your precious time, it is my negligence that caused. 😖