gpt4 book ai didi

xml - 将 xml 节点转换为 typescript 定义的类型

转载 作者:行者123 更新时间:2023-12-04 17:34:42 26 4
gpt4 key购买 nike

我想将 xml 响应转换为 typescript 对象。这就是我所做的:

enum status {
Pending = 1,
Rejected = 5,
Validated = 6
}
type Request = {
totalInDays: number;
status: string;
}

const response = '<ns1:Request>
<ns1:totalInDays>0.5</ns1:totalInDays>
<ns1:status>1</ns1:durationInDays>
<ns1:startDate>22/07/2019</ns1:startDate>
<ns1:endDate>22/07/2019</ns1:endDate>
</ns1:Request>'

const object = response as Request // this is not working

最佳答案

您必须解析 XML 并将其转换为对象。response 对象当前是 string 类型。使用 as 语法,您可以告诉 typescript 将其对待为另一种类型——它不会更改对象本身的类型。

关于如何将XML实体转换为JavaScript对象看here .有了 JavaScript 对象后,您可以使用 as 语法告诉 TypeScript 将其视为 Request

一个例子(使用 xml-js ):

import {xml2js} from 'xml-js' 
// or with require:
// const xml2js = require('xml-js').xml2js;

enum status {
Pending = 1,
Rejected = 5,
Validated = 6
}
interface Request { // Using interface instead of type
totalInDays: number;
status: status; // I think you had a mistake here in your question - should be of type 'status' not 'string'
}

const response = '<ns1:Request>
<ns1:totalInDays>0.5</ns1:totalInDays>
<ns1:status>1</ns1:durationInDays>
<ns1:startDate>22/07/2019</ns1:startDate>
<ns1:endDate>22/07/2019</ns1:endDate>
</ns1:Request>'


const object:Response = xml2js(response) as Response; // as Response might not be needed depending on the libraries typings, if there are any

关于xml - 将 xml 节点转换为 typescript 定义的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57148350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com