如何为TypeScript中onHandlerData函数的data参数实现动态类型定义?
Dynamic Typing for
onHandlerData's data Parameter Got it, let's sort out the dynamic typing for your onHandlerData function. The core issue right now is that your data parameter is locked to UserFormDto["credentials"], but it should match the type of whichever property (credentials/details/address) you're updating via the type parameter.
The fix uses generic types to create a link between the type parameter and the corresponding data type from UserFormDto. Here's how to adjust your code:
// Assuming these interfaces are already defined in your code export interface UserCredentialsDto { /* Your existing type fields */ } export interface UserDetailsDto { /* Your existing type fields */ } export interface UserAddressDto { /* Your existing type fields */ } export interface UserFormDto { credentials: UserCredentialsDto | null; details: UserDetailsDto | null; address: UserAddressDto | null; } const [data, setData] = useState<UserFormDto>({ credentials: null, details: null, address: null, }); // Generic function to tie type and data types together const onHandlerData = <T extends keyof UserFormDto>( type: T, data: UserFormDto[T] // Data type now dynamically matches the selected property ) => { // Rename callback parameter to avoid shadowing the outer `data` variable setData((prevData) => { return { ...prevData, [type]: data }; }); };
What this solves:
- The generic
<T extends keyof UserFormDto>restricts thetypeparameter to only valid keys fromUserFormDto(credentials,details,address). UserFormDto[T]dynamically pulls the exact type of the property specified byT— so if you passtype: 'details', TypeScript will enforce thatdatais of typeUserDetailsDto | null, not just the credentials type.- Renaming the
setDatacallback parameter toprevDataavoids variable shadowing, which is a common source of bugs and TypeScript confusion.
Example valid/invalid calls:
// ✅ Valid: data matches 'credentials' type onHandlerData('credentials', { username: 'johndoe', password: 'secure123' }); // ✅ Valid: data matches 'details' type onHandlerData('details', { firstName: 'John', lastName: 'Doe' }); // ❌ TypeScript error: data doesn't match 'address' type onHandlerData('address', { username: 'wrong-type-here' });
内容的提问来源于stack exchange,提问作者user3887366
相关产品推荐
相关产品推荐

