对于具有可变属性的对象,hasOwnProperty总是返回false



我正在用typescript消费一些k8s对象,我的json看起来像这样:

{
"startTime": "2022-12-01T19:15:58Z",
"taskRuns": {
"task1": {
"pipelineTaskName": "task1Ref",
"status": {
"completionTime": "2022-12-01T19:17:27Z",
"conditions": [
{
"lastTransitionTime": "2022-12-01T19:17:27Z",
"message": "",
"reason": "TaskRunImagePullFailed",
"status": "False",
"type": "Succeeded"
}
]}},
"task2":{same fields as task1},
"task3": {same}
}}

我也有一个包含TaskRun名称的数组,看起来像这样:

["task1","task2",....]
上面对象的相关接口如下:
export interface PipelineRunStatus {
startTime: string;
taskRuns: Truns;
}
export interface Truns {
[key: string]: TaskRun;
}
export interface TaskRUn {<fields from above>}

我正试图将数组元素与taskrun中的可变任务键相匹配,并使用下面的代码提取信息:

type taskRunKey = keyof typeof currentRun.Status.taskRuns
//taskRuns is my string array
taskRuns.map((taskRunName: string) => {
console.log(taskRunName)
if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey))
console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0])
else {
console.log(currentRun?.Status?.taskRuns)
console.log(currentRun?.Status)
}

但是这里打印的是

task1
undefined
Object { TaskRuns: {… task1:{..the object above...}}}
​
task2
undefined
Object { TaskRuns: {… pretty much the object above...}}
​

总之:上面的代码总是以"else"结束语句的分支,尽管存在匹配正确名称的对象属性。有人能解释一下我错过了什么吗?

原来我有几件事是错的:

  1. taskrun "应该是taskrun "由于某种原因,typescript不能反序列化JSON,不区分大小写(像golang那样)。我改变了我的类型export interface PipelineRunStatus { startTime: string; TaskRuns: Truns; }
  2. hasOwnProperty是不正确的,我需要改为:Object.keys(currentRun?.Status?.TaskRuns).includes(taskRunName)

谢谢大家花时间在这上面!

相关内容

  • 没有找到相关文章

最新更新