fix(shallow): types with useStore (#1108)

* fix(shallow): types with useStore

* refactor: simplify types by adding more restrictions
This commit is contained in:
Daishi Kato 2022-07-20 08:48:57 +09:00 committed by GitHub
parent 060c092694
commit 05a4c15cea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 18 deletions

View File

@ -1,24 +1,12 @@
function shallow<
T extends (...args: unknown[]) => unknown,
U extends (...args: unknown[]) => unknown
>(objA: T, objB: U): boolean
function shallow<T extends (...args: any[]) => any>(objA: T, objB: T): boolean
function shallow<
T extends string | number | boolean,
U extends string | number | boolean
>(objA: T, objB: U): boolean
function shallow<T extends string | number | boolean>(objA: T, objB: T): boolean
function shallow<T extends unknown[], U extends unknown[]>(
objA: T,
objB: U
): boolean
function shallow<T extends any[]>(objA: T, objB: T): boolean
function shallow<
T extends Record<string, unknown>,
U extends Record<string, unknown>
>(objA: T, objB: U): boolean
function shallow<T extends Record<string, any>>(objA: T, objB: T): boolean
function shallow<T, U>(objA: T, objB: U) {
function shallow<T>(objA: T, objB: T) {
if (Object.is(objA, objB)) {
return true
}
@ -37,7 +25,7 @@ function shallow<T, U>(objA: T, objB: U) {
for (let i = 0; i < keysA.length; i++) {
if (
!Object.prototype.hasOwnProperty.call(objB, keysA[i] as string) ||
!Object.is(objA[keysA[i] as keyof T], objB[keysA[i] as keyof U])
!Object.is(objA[keysA[i] as keyof T], objB[keysA[i] as keyof T])
) {
return false
}

View File

@ -1,3 +1,4 @@
import create from 'zustand'
import shallow from 'zustand/shallow'
describe('shallow', () => {
@ -54,3 +55,16 @@ describe('shallow', () => {
expect(shallow(firstFnCompare, secondFnCompare)).toBe(false)
})
})
describe('types', () => {
it('works with useStore and array selector (#1107)', () => {
const useStore = create(() => ({
villages: [] as { name: string }[],
}))
const Component = () => {
const villages = useStore((state) => state.villages, shallow)
return <>{villages.length}</>
}
expect(Component).toBeDefined()
})
})