在 TypeScript 中,复杂类型参数可以通过多种方式传递给函数。以下是一些常见的方法:
- 使用接口(Interface)
interface ComplexType {
prop1: string;
prop2: number;
prop3: boolean;
}
function complexFunction(param: ComplexType) {
// 函数实现
}
// 使用
const complexObject: ComplexType = {
prop1: "hello",
prop2: 42,
prop3: true
};
complexFunction(complexObject);- 使用类型别名(Type Alias)
type ComplexType = {
prop1: string;
prop2: number;
prop3: boolean;
};
function complexFunction(param: ComplexType) {
// 函数实现
}
// 使用
complexFunction({
prop1: "hello",
prop2: 42,
prop3: true
});- 使用泛型(Generics)
function complexFunction<T extends { prop1: string; prop2: number }>(param: T) {
// 函数实现
}
// 使用
complexFunction({
prop1: "hello",
prop2: 42,
prop3: true
});- 使用联合类型(Union Types)
type ComplexType =
| { type: "A"; value: string }
| { type: "B"; value: number };
function complexFunction(param: ComplexType) {
// 函数实现
}
// 使用
complexFunction({ type: "A", value: "hello" });
complexFunction({ type: "B", value: 42 });- 使用交叉类型(Intersection Types)
type Type1 = { prop1: string };
type Type2 = { prop2: number };
function complexFunction(param: Type1 & Type2) {
// 函数实现
}
// 使用
complexFunction({ prop1: "hello", prop2: 42 });- 使用函数重载(Function Overloading)
function complexFunction(param: string): string;
function complexFunction(param: number): number;
function complexFunction(param: string | number): string | number {
// 函数实现
}
// 使用
complexFunction("hello");
complexFunction(42);选择哪种方法取决于你的具体需求和代码结构。接口和类型别名通常用于定义复杂的对象结构,泛型用于创建可重用的组件,联合类型和交叉类型用于组合多个类型,而函数重载用于处理不同参数类型的情况。