#Requiring optional parameters

21 messages · Page 1 of 1 (latest)

wild halo
#

Hello, I am attempting to create a type that simply sets the account field of this WalletClient type.

I am doing so as below, but functions that are taking in my LoadedClient still say that account may be undefined:

type LoadedClient = Omit<WalletClient, 'account'> & Required<Pick<WalletClient, 'account'>>
kind pathBOT
#
export type WalletClient<
slate herald
#

A demo might be helpful, looks like it should work to me.

wild halo
#

If you hover over x it will say that it the type includes | undefined:

import { WalletClient } from "viem";

type LoadedClient = Omit<WalletClient, 'account'> & Required<Pick<WalletClient, 'account'>>;

const test = (client: LoadedClient) => {
    const x = client.account;
}
woeful horizon
#

you maybe have exactOptionalPropertyTypes enabled and WalletClient explicitly says | undefined?

#

if you could make a reproduction on the playground that'd probably help

wild halo
wild halo
#
export type WalletClient<
  transport extends Transport = Transport,
  chain extends Chain | undefined = Chain | undefined,
  account extends Account | undefined = Account | undefined,
  rpcSchema extends RpcSchema | undefined = undefined,
> = Prettify<
  Client<
    transport,
    chain,
    account,
    rpcSchema extends RpcSchema
      ? [...WalletRpcSchema, ...rpcSchema]
      : WalletRpcSchema,
    WalletActions<chain, account>
  >
>
woeful horizon
woeful horizon
wild halo
# woeful horizon you can

Oh all my searching said you couldn't, can you tell me how to do that so I can get you an example?

woeful horizon
#

just import it

wild halo
#

Oh I had no clue

stiff shadowBOT
#
sleepingshell#0

Preview:```ts
import {Account, WalletClient} from "viem"

type LoadedClient = Omit<WalletClient, "account"> &
Required<Pick<WalletClient, "account">>

function useAccount(acc: Account) {}

function test(client: LoadedClient) {
useAccount(client.account)
}```

wild halo
#

You can see that it still says that client.account may be undefined

slate herald
#

WalletClient.account is Account | undefined. It is a required property, not an optional property.

#

And Required makes properties required but doesn't affect values of undefined

#

You can do

type LoadedClient = WalletClient & { account: Exclude<WalletClient['account'], undefined> }

or

type LoadedClient = {
    [K in keyof WalletClient]: K extends 'account'
        ? Exclude<WalletClient[K], undefined>
        : WalletClient[K]
}
#

@wild halo

wild halo
#

Thanks so much @slate herald , I wasn't aware of those distinctions. Appreciate your help!