Typescript 无法键入(通过JSDoc)样式化的组件道具
我正在使用VisualStudio代码的功能。 对于那些不熟悉的人,这将启用推断类型,因此您可以从VS代码中获得许多好处,而无需编写类型 不幸的是,它与样式化组件库中基于模板标记的组件存在问题。如果我有如下组件:Typescript 无法键入(通过JSDoc)样式化的组件道具,typescript,styled-components,jsdoc,Typescript,Styled Components,Jsdoc,我正在使用VisualStudio代码的功能。 对于那些不熟悉的人,这将启用推断类型,因此您可以从VS代码中获得许多好处,而无需编写类型 不幸的是,它与样式化组件库中基于模板标记的组件存在问题。如果我有如下组件: const ProductImage = styled.div` background-image: url("${props => props.imagePath}"); `; VS Code在imagePath(但不是props.)下方添加了一条弯曲
const ProductImage = styled.div`
background-image: url("${props => props.imagePath}");
`;
VS Code在imagePath
(但不是props.
)下方添加了一条弯曲的警告线,因为Typescript无法推断props参数的类型
据我所知,Typescript也可以,因此我尝试添加:
/**
* @param {String} [props.imagePath]
* @param {String} [props.alignRight]
*/
const ProductImage = styled.div`
background-image: url("${props => props.imagePath}");
float: ${props => (props.alignRight ? `left` : `right`)}};
`;
。。。但它不起作用
我没有tsconfig.js
,但为了启用JSDoc键入,我尝试将以下内容添加到我的jsconfig.js
:
// Generate d.ts files
"declaration": true,
// This compiler run should only output d.ts files
"emitDeclarationOnly": true
。。。但这也没用
我的问题是:
const Button = styled.TouchableOpacity<ButtonProps>`
opacity: ${(props) => (props.primary ? 0.5 : 1)};
`;
const Button=styled.TouchableOpacity`
不透明度:${(props)=>(props.primary?0.5:1)};
`;
不幸的是,在JSDoc中没有等价物,但是您可以使用cast
因此,您的代码需要类似于:
const Button = styled.TouchableOpacity<ButtonProps>`
opacity: ${(props) => (props.primary ? 0.5 : 1)};
`;
constyled=require('styled-components')。默认值;
/**
*@typedef{{
*imagePath:字符串;
*右对齐:布尔;
*}}ProductImageProps*/
常量产品图像=
/**@type{import('styled-components').ThemedStyledFunction}*/
(styled.div)`
背景图像:url(${props=>props.imagePath});
float:${props=>(props.alignRight?`left`:`right`)};
`;
奇怪的/**type{SomeType}*/(表达式)
构造是如何在JSDoc中执行强制转换的。括号是必需的
请注意,您需要作为开发人员依赖项安装
注2:我在本地设置中使用JSDoc测试了这个,但是我有一个tsconfig.json文件。谢谢!另外,我只想再次强调:
styled.div
周围的括号非常重要!当我将此处的确切注释复制到代码中,但没有添加括号时,警告仍然出现,但当我添加它们时,此解决方案有效(没有tsconfig.json
…甚至没有“声明”:true
或“emitDeclarationOnly”:true
,在我的jsconfig.json
…只是“checkJs”:true
似乎足够了)!顺便说一句,在这种特殊情况下,治愈者最终感觉比疾病更糟糕(即,我宁愿代码中有几行扭曲的代码,也不愿添加所有这些打字废话)。但是我非常感谢这个解释,我强烈怀疑我将来会将它用于其他样式化组件,或者可能用于其他“Javascript中的Typescript”问题!