React Native中API返回数字fontWeight适配文本样式类型问题
Got it, let's tackle this fontWeight mismatch issue between your API and React Native. The core problem here is that React Native expects specific string literals (like "100", "bold") for the fontWeight prop, while your API returns numeric values (100, 200, etc.). Converting the number to a string directly with toString() triggers a type error because TypeScript doesn't recognize the generic string as one of React Native's allowed literal values.
Here are a few solid solutions depending on your needs:
1. Quick Type Assertion (For Trusted API Responses)
If you're certain your API will only return valid numeric values (100-900), you can use a type assertion to tell TypeScript the converted string matches the required literal type:
import { Text } from 'react-native'; import type { TextStyle } from 'react-native'; // Example usage in a Text component <Text style={{ fontWeight: APIResult.fontWeight.toString() as TextStyle['fontWeight'] }} > Your Text Here </Text>
This bypasses the type checker while ensuring you're passing a value React Native understands at runtime.
2. Safe Mapping Function (With Fallback for Invalid Values)
For a more robust approach—especially if there's a chance the API might return an unexpected number—create a mapping function that converts the numeric value to the correct string literal, with a fallback for invalid inputs:
import type { TextStyle } from 'react-native'; const mapFontWeight = (numericWeight: number): TextStyle['fontWeight'] => { const weightMap: Record<number, TextStyle['fontWeight']> = { 100: "100", 200: "200", 300: "300", 400: "400", 500: "500", 600: "600", 700: "700", 800: "800", 900: "900", }; // Return mapped value or default to "normal" if invalid return weightMap[numericWeight] || "normal"; }; // Usage in your component <Text style={{ fontWeight: mapFontWeight(APIResult.fontWeight) }} > Your Text Here </Text>
This ensures you never pass an invalid fontWeight value to React Native, even if the API behaves unexpectedly.
3. Switch Statement Alternative
If you prefer a switch statement over an object map, this works too:
import type { TextStyle } from 'react-native'; const getFontWeight = (weight: number): TextStyle['fontWeight'] => { switch (weight) { case 100: return "100"; case 200: return "200"; case 300: return "300"; case 400: return "400"; case 500: return "500"; case 600: return "600"; case 700: return "700"; case 800: return "800"; case 900: return "900"; default: return "normal"; } };
Why Direct toString() Fails
React Native's fontWeight prop uses a string literal union type ("normal" | "bold" | "100" | ... | "900"), not a generic string. When you call toString() on a number, TypeScript infers the result as a general string, which doesn't match the specific literals React Native expects. Runtime-wise, it might work, but TypeScript will throw an error to prevent potential invalid values from slipping through.
内容的提问来源于stack exchange,提问作者Chris Drackett

