#How to use function with extended generic type (Svelte)

8 messages · Page 1 of 1 (latest)

uncut hedge
#

Hi im not that experienced with TS but im slowly getting the hang of it.
But i currently having an issue where i cant wrap my head around why i'm getting a type error ts(2344). (im using Svelte)

I wrote a generic function that creates a Writable store and extends it with some common methods for data collections (arrays of objects).

// Every DB record has at least a id
interface DBRecord {
  id: number
}

// Svelte store with useful methods for array manipulation
interface CollectionStore<T extends DBRecord> extends Writable<T[]> {
  insertRecord: (data: T) => void
  replaceRecord: (data: T) => void
  removeRecord: (id: number) => void
  sortRecords: (compareFn?: (a: T, b: T) => number) => void
}

// Creates a extended Writable store
declare function collectionStore<T extends DBRecord>(
  value?: T[],
  start?: StartStopNotifier<T[]>
): CollectionStore<T>

But now when i use this function, like:

interface Item {
  id: number
  item: string
}

const itemStore = collectionStore<Item[]>([])

I get the error:

Type 'Item[]' does not satisfy the constraint 'DBRecord'.
  Property 'id' is missing in type 'Item[]' but required in type 'DBRecord'.

I dont understand why. I declared the type Item and it has a id property, so why does it complain about not having id?

prime axle
#
declare function collectionStore<T extends DBRecord>
// vs
collectionStore<Item[]>
#

should be collectionStore<Item>

#

since you already added the array part of the type in the function paramater

uncut hedge
#

omg im so stupid 🤣

#

thank you very much ♥️

prime axle
#

no problem 👍

#

!resolved