TypeScript中如何通过索引获取函数类型的参数类型?接口内函数参数类型获取失败求助
Got it, let's break down how to fix this. The issue with your original code is that you're trying to access NativeMethods.measureLayout directly as if it's a static property, but NativeMethods is an interface defining instance-level methods. To get the type of the measureLayout function, you need to use indexed access on the interface first.
Here's the correct approach:
Step 1: Extract the function type from the interface
Use NativeMethods['measureLayout'] to get the type of the measureLayout method defined in the interface. This tells TypeScript "give me the type of the property named 'measureLayout' in the NativeMethods interface".
Step 2: Use the Parameters utility type
Pass that function type into the Parameters utility type, which returns a tuple of the function's parameter types. Then you can access individual parameters by index.
Full Example Code
// Your original interface export interface NativeMethods { measureLayout( relativeToNativeComponentRef: HostComponent<unknown> | number, onSuccess: MeasureLayoutOnSuccessCallback, onFail: () => void /* currently unused */, ): void; } // Extract parameter types correctly type MeasureLayoutFunction = NativeMethods['measureLayout']; // Get each parameter type type Param1 = Parameters<MeasureLayoutFunction>[0]; // HostComponent<unknown> | number type Param2 = Parameters<MeasureLayoutFunction>[1]; // MeasureLayoutOnSuccessCallback type Param3 = Parameters<MeasureLayoutFunction>[2]; // () => void // Or combine into a single line if you prefer type Param1Short = Parameters<NativeMethods['measureLayout']>[0];
Why Your Original Code Didn't Work
Your original line type Param1 = Parameters<NativeMethod.measureLayout>[0]; (I assume that's a typo for NativeMethods) fails because:
- Interfaces don't have static properties by default; they define the shape of objects.
- To access the type of a method/property within an interface, you must use indexed access (
['propertyName']) instead of dot notation.
This approach works for any interface method where you need to extract parameter or return types using TypeScript's utility types like Parameters, ReturnType, etc.
内容的提问来源于stack exchange,提问作者Noitidart

