【问题标题】:Converting nullable object values to strings in Typescript在 Typescript 中将可为空的对象值转换为字符串
【发布时间】:2019-04-29 12:15:17
【问题描述】:

尝试从正确键入的 GraphQL API 获取响应以便我可以将其与表单一起使用时有点卡住。

我尝试这样做的原因是因为 React 输入期望值是字符串而不是 null。所以我需要将我的可空字段转换为空字符串,然后再将它们传递给 JSX。

这是一个人为的案例,但应该给出要点。

Interface IApiResult {
    title: string;
    description: string | null;
}

// I would expect this to have the shape { title: string, description: string }
//
type NonNullApiResult<T> = {
    [P in keyof T]: string
}

// API result
const result: IApiResult = { title: 'SO TS question', description: null }

// Mapped API result where all values must be strings
const mappedResult: NonNullApiResult<IApiResult> = {
    title: '',
    description: ''
}

// HERE: How can these be merged so that `mappedResult` stays
// of type NonNullApiResult and the data looks like:
//
// mappedResult = { title: 'SO TS question', 'description': '' }

我试过这个..

// Loop through the result and convert null fields to empty strings
for (const key in result) {
    if (result.hasOwnProperty(key)) {

        // `value` is being given the type "any".
        // I would expect it to be "string | null"
        const value = result[key]

        // This passes. I'm guessing because `value` is "any"
        // However, it will still pass the null value into `mappedResult`
        // I would expect this to fail w/ "null not assignable to string"
        mappedResult[key] = value

        // This what I would expect to do
        // mappedResult[key] = value === null ? '' : value
    }
}

mappedResult 仍然是 NonNullApiResult&lt;IApiResult&gt; 类型,但如果我 console.log(mappedResult) 我会在浏览器中看到这个:

{description: null, title: 'SO TS question'}

如果我在 React 中做这样的事情,它会通过,因为它认为 description 是一个字符串

<input name="description" id="description" type="text" value={mappedResult.description} />

但在控制台中我得到了预期的错误:

Warning: `value` prop on `input` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.

感谢任何帮助或建议!这是使用 Typescript 3.1.6 版

【问题讨论】:

    标签: javascript reactjs typescript graphql jsx


    【解决方案1】:

    试试这样的:

    function mapData(data){
      const mappedResult = {};
      for (const key in result) {
        if (result.hasOwnProperty(key)) {
          mappedResult[key] = result[key] || "";
        }
      }
      return mappedResult;
    }
    

    它应该检查对象中的每个键,如果它是假的(null || undefined),则分配一个空字符串。

    进一步澄清一下 - i 变量是什么?

    【讨论】:

    • 抱歉 i 变量是一个错字。打算使用value。更新了原始问题。
    • 我试过你的 sn-p 但它似乎遇到了我最初遇到的同样问题。可以将不正确的类型分配给 mappedResult 道具。 (略微修改为不包含在 func 中)for (const key in result) { if (result.hasOwnProperty(key)) { mappedResult[key] = result[key] || 1 } }。我希望该循环会像 mappedResult.description = 1 那样失败,但它仍然会通过并且 description 错误地以数字而不是字符串结束
    猜你喜欢
    • 2016-05-23
    • 2012-12-08
    • 2021-06-19
    • 1970-01-01
    • 2013-01-24
    • 2012-07-13
    • 1970-01-01
    • 2020-09-27
    • 2014-01-14
    相关资源
    最近更新 更多