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'.
私は、reactnative宣言が文字列を使用せず、可能な文字列のセットのみを許可するのが好きです。
TypeScriptにこれを「絶対」と入力させる方法はありますか?
このposition
フィールドを読み取り専用としてマークできれば、「絶対」と入力すると推測できます。
#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
}
});
これも当てはまります: //github.com/Microsoft/TypeScript/issues/21618#issuecomment -362945112
最も参考になるコメント
私はキャストが好きではなく、可能な限りそれを防ぎますが、回避策は次のとおりです。
エクスポートされるインターフェースがない場合(ここではTextStyle)、フィールドのみをキャストできます: