我有一個值可以回傳字串或物件的情況。
介面定義如下:
interface RoutesType {
projects: string | {
all: string;
favorite: string;
critical: string;
};
價值來自這里:
const routes = {
projects: include('/projects/', {
all: '',
favorite: 'favorite/',
critical: 'critical/'
}
};
當我嘗試訪問時routes.projects.critical,它顯示以下錯誤:
Property 'critical' does not exist on type 'string | { all: string; favorite: string; critical: string;}'.
Property 'critical' does not exist on type 'string'.
有沒有什么合理的方法可以有條件地告訴 TS 我正在嘗試訪問物件routes.projects而不是字串?
uj5u.com熱心網友回復:
projects在訪問它之前,您應該檢查屬性的型別:
if (typeof routes.projects !== 'string') {
// you can now access routes.projects.critical
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/337234.html
下一篇:理解高階JavaScript函式
