Skip to content

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
Collaborator

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.

2 participants