我正在try 为调用API创建自定义类型.我有一个检索股票报价的方法.此方法接受符号的字符串array.我希望返回类型是一个记录,键是那些传入的符号.目前我的设置如下:
import axios from "axios";
export interface IQuote {
readonly askPrice: number;
readonly bidPrice: number;
readonly closePrice: number;
readonly expirationDate: number;
readonly lastPrice: number;
readonly openPrice: number;
}
export type GetSymbolsQuotesResponse<T extends string[]> = Record<
T[number],
IQuote
>;
export async function getSymbolsQuotes<TSymbol extends string>(
symbols: TSymbol[]
): Promise<GetSymbolsQuotesResponse<TSymbol[]>> {
const { data } = await axios.get<GetSymbolsQuotesResponse<TSymbol[]>>(
`/marketdata/quotes`,
{
params: {
symbol: symbols.join(",")
}
}
);
return data;
}
它是这样称呼的:
const stockSymbol = "SPX";
const quotes = await getSymbolsQuotes([stockSymbol]);
// Lovely with autocomplete:
quotes["SPX"].lastPrice;
与自动补全和其他功能配合使用时效果很好.
但是,假设我使用运行时变量(类型为string
)调用它,它不会:
async function getQuotes(stockSymbol: string) {
const quotes = await getSymbolsQuotes([stockSymbol]);
// Object possibly undefined:
quotes[stockSymbol].askPrice;
}
有没有办法绕过这一点,让TypeScrip确信quotes[stockSymbol]
的存在?
当然,可选链接在这里是一个选项(quotes[stockSymbol]?.askPrice
),但我觉得TypeScrip应该知道属性存在于quotes
上,因为它是如何键入的.但我显然漏掉了什么.