Typescript: TS2322:タイプ 'string'はタイプ '"absolute"に割り当てることができません| 「関係節」| 未定義'

作成日 2016年10月09日  ·  3コメント  ·  ソース: microsoft/TypeScript

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に関連しますか?

Question

最も参考になるコメント

私はキャストが好きではなく、可能な限りそれを防ぎますが、回避策は次のとおりです。

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     
    }
});

全てのコメント3件

私はキャストが好きではなく、可能な限りそれを防ぎますが、回避策は次のとおりです。

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     
    }
});
このページは役に立ちましたか?
0 / 5 - 0 評価