【发布时间】: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<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 版
【问题讨论】:
标签: javascript reactjs typescript graphql jsx