如何有条件地告诉 TypeScript 使用哪种数据类型?
How can you conditionally tell TypeScript which data type to use?
我遇到的情况是值可以 return 字符串或对象。
接口定义如下:
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
而不是字符串?
您应该在访问 属性 projects
之前检查它的类型:
if (typeof routes.projects !== 'string') {
// you can now access routes.projects.critical
}
我遇到的情况是值可以 return 字符串或对象。
接口定义如下:
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
而不是字符串?
您应该在访问 属性 projects
之前检查它的类型:
if (typeof routes.projects !== 'string') {
// you can now access routes.projects.critical
}