LoginSignup
0
0

More than 1 year has passed since last update.

【TypeScript】ネストされたオブジェクト型から型を抽出&指定方法

Last updated at Posted at 2022-07-19

ネストされたオブジェクト型から型を抽出&指定方法

ネストされたオブジェクト型からプロパティを指定して、再宣言する方法で色々ググっていい方法を見つけたので備忘録で残します。
下記のようなrelay graphQLでgenerateされた型のcustomerAddressのブロックだけを型としてを再宣言したい場合、


(alias) type DefaultAddressUpdateMutationResponse = {
    readonly customerAddressUpdate: {
        readonly customerAddress: {
            readonly address1: string | null;
            readonly address2: string | null;
            readonly city: string | null;
            readonly zip: string | null;
            readonly province: string | null;
            readonly lastName: string | null;
            readonly firstName: string | null;
            readonly id: string;
        } | null;
    } | null;
}
import DefaultAddressUpdateMutationResponse
DefaultAddressUpdateMutationResponse['customerAddressUpdate']
DefaultAddressUpdateMutationResponse['customerAddressUpdate']['customerAddress']

と指定しても👆の様に参照先のオブジェクト型にor nullがある場合は、アクセスができないため、エラーになります。
対策としてExcludeで条件指定null削除して再宣言します

Exclude<, 除外したいもの>
type GetCustomerAddressUpdateType = Exclude<
  DefaultAddressUpdateMutationResponse['customerAddressUpdate'],
  null
>;
type GetCustomerAddressType = Exclude<
  GetCustomerAddressUpdateType['customerAddress'],
  null
>;

とすればcustomerAddressのブロックをGetCustomerAddressTypeという命名で型宣言ができます。

type GetCustomerAddressType
       customerAddress: {
            readonly address1: string | null;
            readonly address2: string | null;
            readonly city: string | null;
            readonly zip: string | null;
            readonly province: string | null;
            readonly lastName: string | null;
            readonly firstName: string | null;
            readonly id: string;
        }

以上

参考:https://tutorialmore.com/questions-2425024.htm

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0