gpt4 book ai didi

typescript - 为什么字符串会和这个联合类型冲突?

转载 作者:搜寻专家 更新时间:2023-10-30 21:26:29 26 4
gpt4 key购买 nike

我在 react-native 使用 typescript 使用 borderStyle 属性时遇到类型错误。 borderStyle 属性在 react-natives 的声明文件 (index.d.ts) 中声明为联合类型。过去,我只使用字符串在样式定义中设置值,但现在我在 typescript 中遇到错误。

问题:如何正确处理 borderStyle 的样式属性而不违反 typescript 规则?

导致错误的我的 borderStyle 属性:

style: {
borderStyle: 'solid',
},

borderStyle 的类型为:

borderStyle?: "solid" | "dotted" | "dashed";

使用我的样式生成的错误消息:

Type 'string' is not assignable to type '"solid" | "dotted" | "dashed" | undefined'

更新一:如何详细声明样式

  1. 我有一个包含常见样式的 common.styles.ts 文件(这会导致错误)
import { StyleSheet } from 'react-native';
import theme from './theme.styles';

export default {
borders: {
normal: {
borderColor: '#E8E8E8',
borderStyle: 'solid',
},
light: {
borderColor: '#F1F1F1',
borderStyle: 'solid',
},
},
};
  1. 我使用扩展运算符在我的样式声明文件 (Component.styles.ts) 中使用这些常见样式:
import { StyleSheet } from 'react-native';
import common from './../../../styles/common.styles';

export default StyleSheet.create({
container: {
...common.borders.normal,
borderBottomWidth: 1,
},
});

最佳答案

这是一个 referential integrity issue在 typescript 中。在这个 block 中:

style: {  borderStyle: 'solid'}

borderStyle 的类型是字符串,它比"solid"更宽 | “点缀” | “虚线”

尝试

style: {  borderStyle: <"solid" | "dotted" | "dashed">'solid'}

将字符串 solid 转换为正确的类型。

关于typescript - 为什么字符串会和这个联合类型冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54423383/

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