javascript - 将可为空的对象值转换为 Typescript 中的字符串

标签 javascript reactjs typescript graphql jsx

在尝试正确输入 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<IApiResult> 类型但如果我 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

最佳答案

尝试这样的事情:

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

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

并进一步说明 - 什么是 i 变量?

关于javascript - 将可为空的对象值转换为 Typescript 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53505041/

相关文章:

javascript - 在哪里定义 Ember CLI 中的路由?

javascript - ReactJS - 在 ajax 函数呈现数据后执行 javascript 代码

css - react antdesign @media 查询不起作用

typescript - "compileOnSave"Visual Studio Code 中的 TypeScript 源文件

javascript - 如何处理所有元素而不是一个元素的 ajaxSetup 绑定(bind)

javascript - 使用Dust.js(LinkedIn版本) `@eq`来匹配多个值

javascript - contact.map 不是一个函数

reactjs - React Router 6,同时处理多个搜索参数

typescript - 元组的 TypeScript 中的通用类型包装

javascript - 如何使用 TypeScript 键入类似 jQuery 的初始化模式?