Skip to content

narrowing return type of "array.includes" #37890

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
wants to merge 1 commit into from

Conversation

YanagiEiichi
Copy link

The array.includes is used usually to check data type, such as:

const typeList = [ 'apple', 'banana', 'orange' ] as const;

// Return 'apple' | 'banana' | 'orange' is better than any.
function getValueOrDefault(what: any) {
  if (typeList.includes(what)) {
    return what;
  }
  return 'apple';
}

Fixes partial #36275

interface TextMessage { type: 'text', text: string }

interface ImageMessage { type: 'image', url: string }

type Message = TextMessage | ImageMessage;

const message: Message = JSON.parse('{}') as Message;

// Prepare a const type list
const typeList = ['text'] as const;

// Take the `type` as any
let type: any = message.type;

// Narrowing the `type`
if (typeList.includes(type)) {
    // Narrowing the `message`
    if (message.type === type) {
        // It's work
        message.text = message.text.trim();
    }
}

@typescript-bot
Copy link
Collaborator

It looks like you've sent a pull request to update our 'lib' files. These files aren't meant to be edited by hand, as they consist of last-known good states of the compiler and are generated from 'src'. Unless this is necessary, consider closing the pull request and sending a separate PR to update 'src'.

@typescript-bot typescript-bot added the lib update PR modifies files in the `lib` folder label Apr 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lib update PR modifies files in the `lib` folder
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants