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

时间:2018-11-27 17:27:17

标签: 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

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

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

它应该检查对象中的每个键,如果它是伪造的(空||未定义),请为其分配一个空字符串。

还有一些要澄清的地方-i变量是什么?