简体   繁体   English

JSX和Typescript中的字符串文字类型转换

[英]String Literal Type Conversion In JSX and Typescript

I'm having a problem converting a string to a string literal. 我在将字符串转换为字符串文字时遇到问题。

The string literal is defined as follows: 字符串文字的定义如下:

type myLiteral = "cats" | "dogs"

Then I have a component that I want to pass a type from an 'inputted' string. 然后,我有一个组件,希望从“输入”字符串中传递类型。

const myString:string = "cats"
const notQuiteSure:any = myString as myLiteral

React.createComponent(<myComponent inputtedType={notQuiteSure}/>

I'm getting squigglies all over the place. 我到处都乱七八糟。 I have tried using the as keyword and the is keyword to do a 'cast' but nothing seems to work. 我试过使用as关键字和is关键字进行“投射”,但似乎没有任何效果。

Anybody have any ideas how to make this work? 有人对如何进行这项工作有任何想法吗?

这样尝试

const myString: myLiteral = "cats";

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

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