TypeScript版本: 2.1.0-dev.20161008
最小的ReactNative组件来说明问题:
import React, { Component } from 'react';
import { StyleSheet, Text } from 'react-native';
export class Sample extends Component<{}, {}> {
render() {
return (
<Text style={styles.text}>Hello TypeScript</Text> // error on styles, see below
);
}
}
const styles = StyleSheet.create({
text: {
position: 'absolute', // cause of the error: string instead of 'absolute'
top: 0,
left: 0
}
});
错误:
error TS2322: Type '{ position: string; top: number; left: number; }' is not assignable to type 'TextStyle | undefined'.
Type '{ position: string; top: number; left: number; }' is not assignable to type 'TextStyle'.
Types of property 'position' are incompatible.
Type 'string' is not assignable to type '"absolute" | "relative" | undefined'.
我喜欢它的反应式声明不使用字符串,而只允许使用可能的字符串集。
有什么办法让TypeScript推断此类型为“ absolute”?
也许如果我可以将此position
字段标记为只读,则可以推断出键入“ absolute”。
与#10676相关吗?
我不喜欢投射并尽可能防止它,但是这里有一些解决方法:
const styles = StyleSheet.create({
text: {
position: 'absolute',
top: 0,
left: 0
} as React.TextStyle // cast to existing interface
});
当没有接口导出时(这里:TextStyle),我们只能转换字段:
const styles = StyleSheet.create({
text: {
position: 'absolute' as 'absolute', // cast string to type 'absolute'
top: 0,
left: 0
}
});
也可能是这种情况: https :
最有用的评论
我不喜欢投射并尽可能防止它,但是这里有一些解决方法:
当没有接口导出时(这里:TextStyle),我们只能转换字段: