I have this:
types/PretaxAccount.ts
export default interface PretaxAccount {
account_info: object[];
available_balance: string;
display_options: string;
account_type: string;
submit_claims_last_date: string;
effective_date: string;
}
import PretaxAccount from 'types/PretaxAccount';
const getPretaxAccount = async ({
account_type,
flex_account_id,
}: {
account_type: string;
flex_account_id: string;
}) => {
const {
data: { account_detail_info: account }, // <---- notice how I'm renaming the property to "account"
} = await PretaxAccountApi.fetchAccountDetail({
account_id: flex_account_id,
account_type,
});
return { account };
};
I'm trying to cast the account
key's value to PretaxAccount. How would I do this? PretaxAccountApi.fetchAccountDetail is an axios request if that helps.
CodePudding user response:
You can't declare types on the left hand side of the assignment when using destructuring. There's just no syntax for that.
But ideally, PretaxAccountApi.fetchAccountDetail
would return the correct type, and you wouldn't need to case anything. You typically want to destructure values with strongly typed shapes. Then Typescript just does the right thing without any additional types.
If that's not an option for some reason, you can store the result in a typed variable first:
const result: { data: { account_detail_info: PretaxAccount } } =
await PretaxAccountApi.fetchAccountDetail({
account_id: flex_account_id,
account_type,
});
const {
data: { account_detail_info: account },
} = result
CodePudding user response:
In TypeScript, you can use the as keyword or <> operator for type castings.
You can find a quick tutorial with more info here, if you're curious.
BUT, I don't actually think type casting is necessary for what you are trying to do, given the account value matches the PretaxAccount interface.
Are you intending to cast account to PretaxAccount and return this? If so, you can drop the {}.
return account;
Your issue is likely because you had brackets around { account } in the return value. I'd recommend dropping the brackets, and adding a return type for the function of "PretaxAccount" if that's your intent.
Also, I'd break out your parameter definition to a separate interface for readability. Personal preference, but I think it's a bit easier to read as this:
interface AccountIdInfo {
account_type: string;
flex_account_id: string;
}
const getPretaxAccount = async (accountIdInfo: AccountIdInfo): PretaxAccount => {
const { account_type, flex_account_id } = accountIdInfo;
const {
data: { account_detail_info: account }, // <---- notice how I'm renaming the property to "account"
} = await PretaxAccountApi.fetchAccountDetail({
account_id: flex_account_id,
account_type,
});
return account;
};