Is there a way to specify the type of data
in order to include all keys that exist in initialData
plus additional keys from Item
as Partial(optional)
?
class TrackedInstance<Item extends Record<string, any>, InitialData extends Partial<Item> = Partial<Item>>> {
private _data: Partial<Item> = {}
constructor(initialData: InitialData, isNew?: boolean) {
this._data = initialData
}
get data() {
return this._data
}
}
interface User {
name: string
age: number
isAdmin: boolean
}
const userInstance = new TrackedInstance<User>({
name: ''
})
const test1: string = userInstance.data.name // Should be ok
const test2: number = userInstance.data.age // Should throw an error because age can be 'undefined' or 'number'
I believe it should look something like
get data(): Pick
However, it gives an error:
TS2344: Type 'keyof InitialData' does not satisfy the constraint 'keyof Item'.