0

I have a vue composable that uses modals of type { [key: string]: boolean }. My implement is shown below. However, I always get error as shown below the code. How can I fix this issue. Any information will be much appreciated.

export const useTable = <T extends { [key: string]: boolean }>(
  url: string,
  options: { modals: T } = {
    modals: {
      default: false,
      media: false,
    },
  }
) => {}

Error

Type 'Ref<{ default: boolean; media: boolean; }>' is not assignable to type 'T'.

enter image description here

Dickson Afful
  • 708
  • 1
  • 6
  • 20
  • 1
    why are you even using a generic type `T` then you already know all properties and types? – Tobias S. May 05 '22 at 08:47
  • Basically, you can't have a default value on a generic type that extends from another type, because it restricts the assignment. See this answer: https://stackoverflow.com/a/59363875/1628790 – Gabriel Heming May 05 '22 at 08:52
  • It can be extended when the composable is used – Dickson Afful May 05 '22 at 08:52
  • @DicksonAfful If it is extended further, the default value might be incorrect. No? – super May 05 '22 at 08:56
  • @DicksonAfful By extended further here, I mean if `T` would be a subtype of `{ [key: string]: boolean }`. – super May 05 '22 at 08:59
  • Does this answer your question? [How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"?](https://stackoverflow.com/questions/56505560/how-to-fix-ts2322-could-be-instantiated-with-a-different-subtype-of-constraint) – Moshe Jonathan Gordon Radian May 05 '22 at 10:55
  • There has been an explanation of the issue before (https://stackoverflow.com/questions/56505560/how-to-fix-ts2322-could-be-instantiated-with-a-different-subtype-of-constraint) but here is a way to maintain your declaration which compiles - perhaps a possible solution: ```typescript export const useTable = ( url: string, options: { modals: T | { [key: string]: boolean } } = { modals: { default: false, media: false, }, } ) => {} ``` – Moshe Jonathan Gordon Radian May 05 '22 at 10:57
  • URL with the demonstrated solution: https://www.typescriptlang.org/play?#code/FAUwHgDg9gTgLgAgMZQHYGdEFd0gCoCGARgDYgIC8CAPHguHCKgCboIDeCA2gNYgCeALgSYYAS1QBzALrCiUKGQKoEAXwB8ACmAIEWGCWGiJkgDQ6EUCHDFp0wzgFsozAiXsI6AHw7c+QkThxKVkEeUUQZTVoqnYLXWdXdwd43QRmEAAzAiwSOGFs9xBzNLTHEGYxAgK3XBK01XrVYABKSnUOZqA – Moshe Jonathan Gordon Radian May 05 '22 at 10:58

0 Answers0