Skip to content

String enum record can't accessed by declared index. #17702

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Ailrun opened this issue Aug 9, 2017 · 1 comment
Closed

String enum record can't accessed by declared index. #17702

Ailrun opened this issue Aug 9, 2017 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@Ailrun
Copy link

Ailrun commented Aug 9, 2017

TypeScript Version: 2.4.2

Code

Run following code with --noImplicitAny option.

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
enum HTTPError {
  CLIENT_ERROR = 'CLIENT_ERROR',
  SERVER_ERROR = 'SERVER_ERROR',
  UNKNOWN_ERROR = 'UNKNOWN_ERROR',
}

// Example 1
type RequestErrorsMap = Readonly<Record<HTTPError, string>>;
const requestErrorsMap: RequestErrorsMap = {
  CLIENT_ERROR: 'Client has problem.',
  SERVER_ERROR: 'Server has problem.',
  UNKNOWN_ERROR: 'Unknown problem occurs.',
};

declare const index: HTTPError;

requestErrorsMap[index]; // Example 1.1
requestErrorsMap[index as 'CLIENT_ERROR' | 'SERVER_ERROR' | 'UNKNOWN_ERROR']; // Example1.2

// Example 2
type EM = {
  [K in HTTPError]: string;
};
const em: EM = {
  CLIENT_ERROR: 'Client has problem.',
  SERVER_ERROR: 'Server has problem.',
  UNKNOWN_ERROR: 'Unknown problem occurs.',
};

declare const i: HTTPError;

em[i]; // Example 2.1
em[i as 'CLIENT_ERROR' | 'SERVER_ERROR' | 'UNKNOWN_ERROR']; // Example2.2

Expected behavior:
example 1.1, 1.2, 2.1 and 2.2 pass type check

Actual behavior:
only 1.2 and 2.2 pass type check

This makes an issue when dealing with js libraries. (whose type is from lib def file)

@mhegazy
Copy link
Contributor

mhegazy commented Aug 21, 2017

looks like a duplicate of #17288

@mhegazy mhegazy added the Duplicate An existing issue was already created label Aug 21, 2017
@Ailrun Ailrun closed this as completed Sep 5, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants