1

I have some class with the following definition:

export class WorkspaceFilter {
  [key: string]: boolean | string | [string]
}

Then I try to use it in the following function:

const fn = (filter: WorkspaceFilter, key: string) => {
  if (Array.isArray(filter[key]) {
    console.log(filter[key].length)
  }
}

The error is Property 'length' does not exist on type 'false'. Obviously, that's because boolean is one of the accepted types. But I'm checking the type manually! How to shut up Typescript after that exact js type check?

2
  • 1
    I suspect it's more of a problem that you use filter[key] and TS things it might be a different key. Extract to a local variable const myFilter = filter[key] and use that Commented Apr 9, 2020 at 9:55
  • I think this might be the same bug as here Commented Apr 9, 2020 at 10:50

1 Answer 1

1

if you check for it to be an array, you can tell typescript that it's dealing with an array:

export class WorkspaceFilter {
  [key: string]: boolean | string | [string]
}

const fn = (filter: WorkspaceFilter, key: string) => {
  if (Array.isArray(filter[key])) {
    console.log((filter[key] as string[]).length)
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this works. But am I the only one who finds that a bit stupid? Typescript does not help here - if I remove Array.isArray condition and pass boolean, the code will throw an error. Typescript does not help here in any way, it's just an obstacle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.