简体   繁体   中英

Typescript - Type 'string' is not assignable to type 'boolean'

I have following typescript code:

const parentItem= this.links.find((link) => {
  return urlArr.find((urlWord) => {
    return !!(urlWord === link.route.split('./')[1])
  })
});

// link.route.split('./')[1] is a string
// urlWord is also a string
// urlArr is array of strings
// links is an array of objects

and typescript keeps on complaining:

.component.ts(11,59): error TS2322: Type 'string' is not assignable to type 'boolean'.

The code works fine in chrome console.

This may look like similar to this question but even after reading it I couldn't figure out where the problem is.

As noted in the comments, I need to return a boolean in the find function. So doing the following ensure that the result of inner find is converted to a boolean.

const parentItem= this.links.find((link) => {
  // convert to boolean
  return !!(urlArr.find((urlWord) => {
    return urlWord === link.route.split('./')[1]
  }));
});

The code above now returns a matched link object or undefined.

Just update your typescript and/or typings. There is no any error in your code

declare var links: { route: string }[]
declare var urlArr: string[]

const parentItem = links.find(link => urlArr.find(urlWord => urlWord === link.route.split('./')[1]));

as in current version of typescript defines find method as

(method) Array<string>.find(predicate: (value: string, index: number, obj: string[]) => unknown, thisArg?: any): string | undefined (+1 overload)

note unknown instead of boolean - you may return anything you want.

But as you actually don't need result of inner find (unless you can find an empty string), you can use some instead of it.

Facing with same issue by html control disabled="disabled" changed to [disabled]="true" and problem was solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM