[英]Typescript type inference on dynamically accessed object properties
interface CustomResponse {
data: string;
status: number;
[key: string]: string | number;
}
const RESPONSE_PROPS = {
DATA: "data",
STATUS: "status",
};
const response: CustomResponse = {
data: "test",
status: 200,
};
let dataWrong: string = response[RESPONSE_PROPS.DATA];
let dataRight: string = response.data;
dataWrong
gets the error dataWrong
获取错误
Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'
In cases like above, how to get dataWrong
infer right type in typescript? 在上面这样的情况下,如何获取dataWrong
在打字稿中推断出正确的类型? Is type assertion (better type guards) the only way? 类型断言(更好的类型守卫)是唯一的方法吗?
RESPONSE_PROPS.DATA
is typed as string
if you use an as const
assertion (which will make the compiler keep the string literal type "data"
for RESPONSE_PROPS.DATA
) it works as expected: 如果使用as const
断言(这将使编译器保持RESPONSE_PROPS.DATA
的字符串文字类型为"data"
),则RESPONSE_PROPS.DATA
将键入为string
它按预期工作:
interface CustomResponse {
data: string;
status: number;
// [key: string]: string | number; not necessary for the code to work
}
const RESPONSE_PROPS = {
DATA: "data",
STATUS: "status",
} as const;
const response: CustomResponse = {
data: "test",
status: 200,
};
let dataWrong: string = response[RESPONSE_PROPS.DATA];
let dataRight: string = response.data;
Note: If the string literal type is used to index you don't really need the index signature. 注意:如果字符串文字类型用于索引,则不需要索引签名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.