إصدار TypeScript: 2.1.0-dev.20161008
Minimal ReactNative Component لتوضيح المشكلة:
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'.
يعجبني أن التصريح التفاعلي لا يستخدم سلسلة نصية ، ولكنه يسمح فقط بمجموعة السلاسل الممكنة.
هل هناك أي طريقة للسماح لـ 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
}
});
هذا متعلق بـ https://github.com/Microsoft/TypeScript/pull/19966.
يمكن أن يكون هذا هو الحال أيضًا: https://github.com/Microsoft/TypeScript/issues/21618#issuecomment -362945112
التعليق الأكثر فائدة
لا أحب الإرسال وأمنعه قدر الإمكان ، ولكن إليك الحلول:
عندما لا تكون هناك واجهة يتم تصديرها (هنا: TextStyle) ، يمكننا فقط إلقاء الحقل: