Skip to content
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

Support the new 4.0 definition of isArray #102413

Merged
merged 1 commit into from Jul 13, 2020

Conversation

orta
Copy link
Contributor

@orta orta commented Jul 13, 2020

This PR relates to microsoft/TypeScript#39258

Effectively, it brings your isArray type check inline with the version in this PR ^

Example:

// Original version, uses any 
export function isArrayOld(array: any): array is any[] {
      return Array.isArray(array);
}

// New, funky-looking, but retains readonly safely
function isArray<T>(array: T | {}): array is T extends readonly any[] ? (unknown extends T ? never : readonly any[]) : any[] {
    return Array.isArray(array);
}

const mutableArray: string[] = []
const immutableArray: readonly string[] = []

if (isArray(mutableArray)) {
  mutableArray.push("")
}

// Fails correctly
if(isArray(immutableArray)) {
  immutableArray.push("")
  // would error here
}


/// Previous behavior

if (isArrayOld(mutableArray)) {
  mutableArray.push("")
}

if (isArrayOld(immutableArray)) {
  immutableArray.push("")
  // No error on pushing to an readonly array
}

Playground Link

@mjbvz mjbvz merged commit d47ddb6 into microsoft:master Jul 13, 2020
@mjbvz
Copy link
Contributor

mjbvz commented Jul 13, 2020

Thanks!

@mjbvz mjbvz added this to the July 2020 milestone Jul 13, 2020
Charles-Gagnon pushed a commit to Charles-Gagnon/vscode that referenced this pull request Jul 14, 2020
@github-actions github-actions bot locked and limited conversation to collaborators Aug 27, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants