Typescript: TS2322: El tipo 'cadena' no se puede asignar al tipo '"absoluto" | "relativo" | indefinido '

Creado en 9 oct. 2016  ·  3Comentarios  ·  Fuente: microsoft/TypeScript

Versión de TypeScript: 2.1.0-dev.20161008

Componente ReactNative mínimo para ilustrar el problema:

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

Me gusta que la declaración reactiva no use una cadena, sino que solo permita el conjunto de cadenas posibles.

¿Hay alguna forma de permitir que TypeScript infiera esto para escribir 'absoluto'?
Tal vez si pudiera marcar este campo position como de solo lectura, podría inferir escribir 'absoluto'.

Relacionado con # 10676?

Question

Comentario más útil

No me gusta la transmisión y la evito tanto como sea posible, pero aquí hay soluciones:

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

Cuando no se exporta una interfaz (aquí: TextStyle), podemos enviar solo el campo:

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

Todos 3 comentarios

No me gusta la transmisión y la evito tanto como sea posible, pero aquí hay soluciones:

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

Cuando no se exporta una interfaz (aquí: TextStyle), podemos enviar solo el campo:

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

Este también puede ser el caso: https://github.com/Microsoft/TypeScript/issues/21618#issuecomment -362945112

¿Fue útil esta página
0 / 5 - 0 calificaciones

Temas relacionados

jbondc picture jbondc  ·  3Comentarios

uber5001 picture uber5001  ·  3Comentarios

fwanicka picture fwanicka  ·  3Comentarios

Antony-Jones picture Antony-Jones  ·  3Comentarios

siddjain picture siddjain  ·  3Comentarios