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?
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
}
});
Esto está relacionado con https://github.com/Microsoft/TypeScript/pull/19966.
Este también puede ser el caso: https://github.com/Microsoft/TypeScript/issues/21618#issuecomment -362945112
Comentario más útil
No me gusta la transmisión y la evito tanto como sea posible, pero aquí hay soluciones:
Cuando no se exporta una interfaz (aquí: TextStyle), podemos enviar solo el campo: