You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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 the type parameter to only valid keys from UserFormDto (credentials, details, address).
  • UserFormDto[T] dynamically pulls the exact type of the property specified by T — so if you pass type: 'details', TypeScript will enforce that data is of type UserDetailsDto | null, not just the credentials type.
  • Renaming the setData callback parameter to prevData avoids 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:42:53