1. (type parameter) T in identity<T>(arg: T): T
function identity<T>(arg: T): T {
return arg;
}
2. (type parameter) U in <U>(arg: U): (U)
let myIdentity
interface Person {
name: string;
age: number;
}
// `keyof Person` here creates a union type of "name" and "age", other strings will not be allowed
function printPersonProperty(person: Person, property: keyof Person) {
console.log(`${person[property]}`);
}
let person = {
name: "Max",
age: 27
};
printPersonProperty(person, "age"); // Printing person property name: "Max"
4.2 keyof with index signatures
type StringMap = {
[key: string]: unknown
};
// `keyof StringMap` resolves to `string` here
function createStringPair(property: keyof StringMap, value: string): StringMap {
return {
[property]: value
};
}
console.log(createStringPair("Lionel","Hi"));
5. How to Define and Use Generic Components in React
— 5.1 Function
interface MyComponentProps<T> {
data: T;
// Add additional props specific to your component
}
function MyComponent<T>({ data }: MyComponentProps<T>) {
return (
<div>
{/* JSX content */}
</div>
);
}
— 5.2 Arrow Function
Để tránh sự mơ hồ giữa các tham số kiểu chung và một jsxthành phần, bạn thêm dấu phẩy theo sau tham số kiểu để phân biệt nó với JSX.Element.