如何从联合类型中单独选取ImageURISource类型?
Absolutely! You can pull out the ImageURISource type from the union exported by React Native using TypeScript's conditional type utilities. Here's a reliable way to do it:
Step 1: Use a Conditional Type to Filter the Union
React Native's ImageSourcePropType is a union of ImageURISource, ImageRequireSource, and potentially other types. We can create a utility type that filters this union to only keep the member with the uri property (which is the signature of ImageURISource):
import type { ImageSourcePropType } from 'react-native'; // Utility type to extract the URI-specific source type from the union type ExtractURISource<T> = T extends { uri: string | undefined } ? T : never; // Now we have our standalone ImageURISource type type ImageURISource = ExtractURISource<ImageSourcePropType>;
How This Works
The conditional type ExtractURISource<T> iterates over every member of the union type T. It checks if the member has a uri property (matching the shape of ImageURISource), and only retains that member. Any other types in the union (like the numeric ImageRequireSource) get excluded by the never branch.
Example Usage
Once you've defined the type, you can use it to explicitly type variables that should only accept URI-based image sources:
// Valid: This matches the ImageURISource structure const remoteImage: ImageURISource = { uri: 'https://your-domain.com/image.png', width: 300, height: 300, headers: { Authorization: 'Bearer token' } }; // Invalid: This would throw a type error, since it's a require() source // const localImage: ImageURISource = require('./assets/image.png');
Why This Is Better Than Direct Internal Imports
You might notice that ImageURISource is defined internally in React Native's codebase, but it's not exported publicly. While you could import it directly from the internal module path, this is risky—internal module structures can change between React Native versions, breaking your code. Using the conditional type approach relies only on the public ImageSourcePropType export, making your code more maintainable.
内容的提问来源于stack exchange,提问作者Noitidart

