我有一個用于發出 HTTP 請求的組件,其中一個屬性 ( 'address') 應該是可選的,因為我在呼叫該函式的組件之一中不需要它。
我之前的做法是使用 Partial 實用程式型別,但我想更具體地使用 Pick。
舊版:
export type Trip = {
address: string
product: string
no: number
customer: string
}
export const usePostTrip = () => {
const queryClient = useQueryClient()
const mutation = useMutation(
async (data: Partial<Trip>) => { // This is achieved with Partial
const url = `${BASE_URL}/trip`
return axios.post(url, data ).catch((e) => console.log(e.message))
},
)
return mutation
}
這是我目前的解決方案,我認為這不是最好的解決方案。這種情況有更好的解決方案嗎?
export type Trip = {
address: string
product: string
no: number
customer: string
}
type tripWithoutAddress = Pick<
Trip, 'product'| 'no'
>
type tripsWithAddress = Pick<
Trip, 'product'| 'no' | 'address'
>
export const usePostTrip = () => {
const queryClient = useQueryClient()
const mutation = useMutation(
async (data: tripWithoutAddress | tripsWithAddress) => { // This is achieved with Pick
const url = `${BASE_URL}/trip`
return axios.post(url, data).catch((e) => console.log(e.message))
},
)
return mutation
}
uj5u.com熱心網友回復:
我認為吉米的回答很好,但是:
如果您更改了address屬性 on Trip(例如 from stringto number),您還必須手動更改可選版本以保持型別一致性。
通過使用Pickand Partial,您可以引數化地從 派生型別Trip:對address屬性的任何更改Trip也將在派生型別中自動更改:
TS游樂場
type Trip = {
address: string;
customer: string;
no: number;
product: string;
}
type TripWithOptionalAddress = Omit<Trip, 'address'> & Partial<Pick<Trip, 'address'>>;
declare const t: TripWithOptionalAddress;
t.address // string | undefined
uj5u.com熱心網友回復:
這不是清楚你的問題說,但它聽起來像你想的一個版本Trip,其中僅該address屬性是可選的,和其他人保持必需的。這可以通過省略該address屬性然后通過使用交集型別使用可選修飾符將其添加回來來實作。
export type Trip = {
address: string;
product: string;
no: number;
customer: string;
};
export type TripWithOptionalAddress = Omit<Trip, "address"> & { address?: string; };
// All fields are required.
const trip: Trip = {
address: "123 TypeScript Ave",
product: "Stack Overflow",
no: 123,
customer: "Greg",
};
// `address` is missing.
const tripWithoutAddress: TripWithOptionalAddress = {
product: "Stack Overflow",
no: 123,
customer: "Greg",
};
// `address` is still allowed, if present.
const tripWithAddress: TripWithOptionalAddress = trip;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/394478.html
標籤:打字稿
下一篇:在畫布中呼叫函式
