在尝试正确输入 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/