我正试图将TypeScript集成到我们的项目中,到目前为止,我偶然发现了一个关于styled-components库的问题.

考虑这个组件

import * as React from "react";
import styled from "styled-components/native";
import { TouchableOpacity } from "react-native";

// -- types ----------------------------------------------------------------- //
export interface Props {
  onPress: any;
  src: any;
  width: string;
  height: string;
}

// -- styling --------------------------------------------------------------- //
const Icon = styled.Image`
  width: ${(p: Props) => p.width};
  height: ${(p: Props) => p.height};
`;

class TouchableIcon extends React.Component<Props> {
  // -- default props ------------------------------------------------------- //
  static defaultProps: Partial<Props> = {
    src: null,
    width: "20px",
    height: "20px"
  };

  // -- render -------------------------------------------------------------- //
  render() {
    const { onPress, src, width, height } = this.props;
    return (
      <TouchableOpacity onPress={onPress}>
        <Icon source={src} width={width} height={height} />
      </TouchableOpacity>
    );
  }
}

export default TouchableIcon;

下面的一行抛出3个错误,性质相同

键入{source:any;width:string;height:string;}不可转让

不完全确定这是什么以及如何修复它,我是否需要在Icon或类似的东西上声明这些?

EDIT:类型脚本v2.6.1,样式化组件v2.2.3

推荐答案

This answer is outdated, the most current answer is here: 100

据我所知,目前还没有正式的方法要做到这一点,你可以通过一些技巧来解决.首先,创建一个包含以下内容的withProps.ts文件:

import * as React from 'react'
import { ThemedStyledFunction } from 'styled-components'

const withProps = <U>() => <P, T, O>(fn: ThemedStyledFunction<P, T, O>) =>
    fn as ThemedStyledFunction<P & U, T, O & U>

export { withProps }

现在,在你的.tsx个文件中,像这样使用它:

// ... your other imports
import { withProps } from './withProps'

export interface IconProps {
  onPress: any;
  src: any;
  width: string;
  height: string;
}

const Icon = withProps<IconProps>()(styled.Image)`
  width: ${(p: IconProps) => p.width};
  height: ${(p: IconProps) => p.height};
`;

你应该可以走了.这绝对是not个理想值,希望能很快在TS中为模板文本提供泛型,但我想现在这是最好的 Select .

信用是在信用到期的地方给出的:我从here复制粘贴了这个

Typescript相关问答推荐

无需刷新即可让现场访客逆变

如何为ViewContainerRef加载的Angular组件实现CanDeactivate保护?

JS Redux Devtools扩展不工作

如何将类型从变量参数转换为返回中的不同形状?

输入元素是类型变体的对象数组的正确方法是什么?'

打字脚本中泛型和直接类型重新映射的不同行为

如何根据特定操作隐藏按钮

在不更改类型签名的情况下在数组并集上映射文字

使用TypeScrip根据(可选)属性推断结果类型

如何使默认导出与CommonJS兼容

ApexCharts条形图未显示最小值.负值

常量类型参数回退类型

如何在省略一个参数的情况下从函数类型中提取参数类型?

如何按属性或数字数组汇总对象数组

自动通用回调

打字错误TS2305:模块常量没有导出的成员

编剧- Select 动态下拉选项

从联合提取可调用密钥时,未知类型没有调用签名

带动态键的 TS 功能

为什么 Typescript 无法正确推断数组元素的类型?