1

I am using a function from an external library that returns an object where there is a particular property that is typed as number, but since it operates on my data, I know it is in fact just an union of 1 | 2. How can I override it to be more specific?

/* original type: */ { id?: number }
/*  desired type: */ { id: keyof typeof CHAINS_ENUM }
src/myFile.ts
import { someFunction, setIds} from '@some-library/core'

setIds([1, 2]) // <- simplification
const { id } = someFunction() // id: number
node_modules/@some-library/core/dist/index.d.ts
export { someFunction } from './provider'
node_modules/@some-library/core/dist/provider.d.ts
import { SomeInterface } from './types';
export declare function someFunction(key?: string): SomeInterface<T>;
node_modules/@some-library/core/dist/types.d.ts
export interface AnotherInterface { ... }
export interface SomeInterface<T = any> extends AnotherInterface {
  id?: number
}

Simplified code snippet with the actual library in question:

import { useWeb3React } from '@web3-react/core'

const MyComponent: React.FC = () => {
  const { chainId } = useWeb3React()      // chainId: number
  return <MyForm baseChainId={chainId} /> // type 'number' is not assignable to type 0 | 1 ; baseChainId: keyof typeof CHAINS_ENUM
}
Qwerty
  • 29,062
  • 22
  • 108
  • 136

1 Answers1

0

I wish it was possible to override this on a global level, without having to remember to import the library from a different location, but at least it works.

src/utils/web3.ts
import { useWeb3React as useWeb3React_ } from '@web3-react/core'

export const useWeb3React: < T = any >(key?: string) => Modify<
  ReturnType<typeof useWeb3React_<T>>,
  { chainId: SupportedChainIds }
> = useWeb3React_ as any

declare global {
  type SupportedChainIds = 1 | 4
}

In the desired file

// import { useWeb3React } from '@web3-react/core' // before
import { useWeb3React } from 'src/utils/web3'      // after

const MyComponent: React.FC = () => {
  const { chainId } = useWeb3React()      // chainId: 1 | 4
  return <MyForm baseChainId={chainId} /> // no error ✔
}

Modify<Original, Newtype> type

Overriding interface property type defined in Typescript d.ts file

Qwerty
  • 29,062
  • 22
  • 108
  • 136