首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法将对象文本赋值给`...`,因为对象文本[1]中缺少属性`...`,但该属性存在于`...`中

无法将对象文本赋值给`...`,因为对象文本[1]中缺少属性`...`,但该属性存在于`...`中
EN

Stack Overflow用户
提问于 2018-05-31 17:37:38
回答 1查看 7.8K关注 0票数 9

我是一个新的流程,目前正在处理一个严格的流程项目。我有一个类型别名被传递给一个类。该代码片段可以在here中找到

代码语言:javascript
复制
// @flow strict

export type CustomType = {
  a: string,
  b: boolean,
  c: boolean,
  d: boolean,
  e: boolean
};
let d = true;
let b = true;
let customType:CustomType = {
        d,
        b,
        c: true,
 }

class Custom{
  constructor(customType = {}) {}
}

let custom = new Custom(customType);

在传递对象时,并不是所有属性customType都存在。这里最好的解决方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-31 20:23:31

您可以将CustomType对象的键键入为optional

(Try)

代码语言:javascript
复制
// @flow strict

export type CustomType = {
  a?: string,
  b?: boolean,
  c?: boolean,
  d?: boolean,
  e?: boolean
};
let d = true;
let b = true;
let customType: CustomType = {
        d,
        b,
        c: true,
 }

class Custom{
  constructor(customType: CustomType = {}) {}
}

let custom = new Custom(customType);

或者,您可以使用$Shape<T>。它只允许你传递你感兴趣的密钥:

(Try)

代码语言:javascript
复制
// @flow strict

export type CustomType = {
  a: string,
  b: boolean,
  c: boolean,
  d: boolean,
  e: boolean
};
let d = true;
let b = true;
let customType: $Shape<CustomType> = {
        d,
        b,
        c: true,
 }

class Custom{
  constructor(customType: $Shape<CustomType> = {}) {}
}

let custom = new Custom(customType);
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50621164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档