简体   繁体   English

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

[英]Converting nullable object values to strings in Typescript

A little stuck trying to get the response from a GraphQL API typed properly so that I can use it with forms. 尝试从正确键入的GraphQL API获取响应时有些卡住,以便可以在表单中使用它。

The reason I'm trying to do this is because React inputs expect values to be strings and not null. 我尝试这样做的原因是因为React输入期望值是字符串而不是null。 So I need to convert my nullable fields to empty strings before passing them on to the JSX. 因此,我需要先将可为空的字段转换为空字符串,然后再将其传递给JSX。

This is a bit of a contrived case but should give the gist. 这是一个人为的情况,但应该给出要点。

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': '' }

I tried this.. 我尝试过这个

// 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 is still of type NonNullApiResult<IApiResult> but if I console.log(mappedResult) I get the this in the browser: mappedResult仍然是NonNullApiResult<IApiResult>类型,但是如果我console.log(mappedResult)我会在浏览器中得到这个:

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

If I then do something in React like this it passes because it thinks description is a string 如果我然后在React中像这样做某事,它就会通过,因为它认为description是一个字符串

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

But in the console I get the expected error: 但是在控制台中,我得到了预期的错误:

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

Any help or suggestions are appreciated! 任何帮助或建议,不胜感激! This is using Typescript version 3.1.6 这是使用Typescript版本3.1.6

Try something like this: 尝试这样的事情:

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

It should check each key in object, and if it is a falsy one (null || undefined) assign it an empty string. 它应该检查对象中的每个键,如果它是伪造的(空||未定义),请为其分配一个空字符串。

And to clarify some more - what is i variable? 并澄清更多- i变量是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM