我正在進行格式的 API 呼叫url/ids=[id1,id2,id3]并回傳表單的物件{ id1: {...}, id2: {...}, id3: {...} }
我可以將其鍵入為interface ApiResponse { [key: number]: ResponseShape },但實際上我有更多的型別資訊,因為該型別丟失了輸入的 id 和回應物件的鍵之間的關系。
有沒有辦法在型別中使用變數ids?我知道 TS 是編譯時間,但我希望我適用于以下場景:
function apiCall(ids: number[]) {
const someRandomNumber = 10;
fetch('url').then(
res => {
const data = res.json() as ApiResponse<ids>;
// fine to access by the id
const works = data[ids[0]];
// undefined, because 5 isn't one of the ids we requested so won't be in the reponse type.
const wontWork = data[someRandomNumber]
}
);
}
我猜這不存在,因為它非常小眾并且正好在編譯時應該發生的事情的邊界上,但我希望有一種方法可以type ApiResponse<T extends number[]> = { [id in T[number]]: ResponseShape }將 ids 引數作為型別傳遞
uj5u.com熱心網友回復:
如果您制作apiCall通用然后使用T[number]來獲取所有傳遞的 ID 的聯合,那么您可以構建一個記錄,其中鍵是這些數字。
type ApiResponse<T extends number> = Record<T, 'foo'>;
function apiCall<T extends readonly number[]>(ids: T) {
return fetch('url')
.then(res => res.json()) as Promise<ApiResponse<T[number]>>;
}
apiCall([1, 2] as const)
.then((result) => {
console.log(result[1]); // Allowed
console.log(result[3]); // Not allowed
});
您必須確保傳遞一個元組(如[1, 2] as const)而不是 anumber[]以便在腳本中保留單個 ID 的型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419257.html
標籤:
