Typescript: TS2322: Der Typ 'Zeichenfolge' kann nicht dem Typ '"absolut" | zugewiesen werden "relativ" | nicht definiert'

Erstellt am 9. Okt. 2016  ·  3Kommentare  ·  Quelle: microsoft/TypeScript

TypeScript-Version: 2.1.0-dev.20161008

Minimale reaktive Komponente zur Veranschaulichung des Problems:

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:

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'.

Ich mag es, dass die reaktivative Deklaration keine Zeichenfolge verwendet, sondern nur die Menge möglicher Zeichenfolgen zulässt.

Gibt es eine Möglichkeit, TypeScript auf den Typ 'absolut' schließen zu lassen?
Wenn ich dieses position -Feld als schreibgeschützt markieren könnte, könnte dies möglicherweise auf die Eingabe von 'absolut' schließen.

Bezogen auf # 10676?

Question

Hilfreichster Kommentar

Ich mag Casting nicht und verhindere es so weit wie möglich, aber hier sind Problemumgehungen:

const styles = StyleSheet.create({
    text: {
        position: 'absolute',
        top: 0,
        left: 0     
    } as React.TextStyle // cast to existing interface
});

Wenn keine Schnittstelle exportiert wird (hier: TextStyle), können nur Felder umgewandelt werden:

const styles = StyleSheet.create({
    text: {
        position: 'absolute' as 'absolute', // cast string to type 'absolute'
        top: 0,
        left: 0     
    }
});

Alle 3 Kommentare

Ich mag Casting nicht und verhindere es so weit wie möglich, aber hier sind Problemumgehungen:

const styles = StyleSheet.create({
    text: {
        position: 'absolute',
        top: 0,
        left: 0     
    } as React.TextStyle // cast to existing interface
});

Wenn keine Schnittstelle exportiert wird (hier: TextStyle), können nur Felder umgewandelt werden:

const styles = StyleSheet.create({
    text: {
        position: 'absolute' as 'absolute', // cast string to type 'absolute'
        top: 0,
        left: 0     
    }
});
War diese Seite hilfreich?
0 / 5 - 0 Bewertungen

Verwandte Themen

RyanCavanaugh picture RyanCavanaugh  ·  205Kommentare

disshishkov picture disshishkov  ·  224Kommentare

sandersn picture sandersn  ·  265Kommentare

Gaelan picture Gaelan  ·  231Kommentare

jonathandturner picture jonathandturner  ·  147Kommentare