泛型
因为 TypeScript 是一个结构类型系统,所以类型参数仅在作为成员类型的一部分使用时才会影响结果类型。例如,
Because TypeScript is a structural type system, type parameters only affect the resulting type when consumed as part of the type of a member. For example,
interface Empty<T> {}
let x: Empty<number>;
let y: Empty<string>;
x = y; // OK, because y matches structure of x
xb7yQT45qGdnHcTcEXXhbkiS2Gi04vBOMBZ2qPN5saJ6K1mFSSLP3Agk1AGKitFXbYa603knbPEjftbm0hHScNXUvFBsFuyo4KN2y9qCjJ3MvrMFIbCtrtcDX7K5GZCvCx/W2ZM8LbdBIEdIU2EBig0UJsJWnr+rpr04cXslFDnHdofX+wYSkjCBmekGR4t7zzsOScb6M7Z/HRoRubO9B4ETRfyl6VsQ0CcKGpvCAjoRM1a1+Nbq/qaueZGfUCAgDrMQhhUD/gnvATHPcTeWjsbBz9Osj/XBvZKljCcwv9lroTn0tyeE1pbDlic7eDH3UOInRQQMw8p4GGafpK8XOlfMaMWfeQBLOOE8xbBFoc1HDL0OFA8i6/+nhf2ZsKDQ3XvOdS/qtA/WP15rMDC7KnuNgcefOfapaBjfeCeY3HgoK3gdjMbXiZuI9xtz/58Vc9nnf9icvmi9jfE/fuiOg8cNyBmrLPjAT0oKi/k6z2UADUcuvPjcoM7lGgBYNfyG5cBuuiTdEdmx4hogmP1qw5/sjNLNz0cd4ATXYVXiMsbnM5XoS8gx3hURVol1t9305XsVGBPiaNfUEhltZ/pq3GP59MwBqkc0AuEwdyg0eFztgK1RAH7WjJv9b4Rd8gJpWTo4ISesQdb1IdPAEUBwOg==
interface NotEmpty<T> {
data: T;
}
let x: NotEmpty<number>;
let y: NotEmpty<string>;
x = y; // Error, because x and y are not compatible
xe6IXKqhFyrOWYAhD4F2ximp7/CYlZhQZVGZmMBjN3R3hya2HrV8DHnzhHp7FLF/vuL5izLfGp6XCUUzL65qKkzDrCoNI2iC5kc9UM0Nw0whbjc1lOpMrb9EKZ+lDJwg0LYjbi2wc/xbjGVwdnqf0Fsok7ka7I/rI0ikDmAGbZL6lCXH6Bi1hM67naUyqriRiKhRTElRTrFnm1Lds4XAWdQ+jUICcioA/5L5g3OtLA6dyh8xYciWt9I8YWvW186e7TXFanv4BXEC2bIeA+6aMw==
x2cNN1bgtpi7u3nPjXF0/jcGQTpXcZcyXRkB2jxnG1Bvc0dPZDmpdtfc6lbcIlXjtKJlKYGDnEO+JAj7H1A3BpqVmDd8ArAf/nZ8AbpazVZy7FvnwOu45M0xOqpiiQS6a/u/DD8RYK65fICwlC1QdWUGzL3NzHRdgjoHK+j2xr29cBq0DR3Vcc7q4Kuc+H6SBSl3edufY6kJ0ND2GTlJBFQXnp4noYf4i2Z3bOaVGsEVGwgXtKPsh+XqQQZG8H8Ie2nk8EHT8tlW50elQdqvNhmg0VO33sKtOhY0rc28XHVZ7BjraJAXyJipwo9ZKllRC+XSycopR/n2orCaSHMUNDwOCkEXPKIOA+7dQ7bV6QdN1ljoz8hAPGmjJgzDcr9nSczLItqJ3KFtAL8hMdB6Lu+CQIkEM3n80QswczFN1FxqKGYMcZQenEvFRySNg/nmLreUzFIniaiW+AhH76SwlUtU35dKb4UskT7Qr2BLRXuHJezECZnbYfBoR7ipQ0kbhywj4iJgZi8gOumzPucOHU0UqMvZT6Jwpk8lDnk6Qg6+LXUT8XzNWQjM+SANIEGtzEzAqqDGLJnxPM8183YEHX/qvDu5N+vJqLuW33tbu8uiMu60jxPy9W/3nOcoQRnUqjp4J/qJXoAIKNdTxQbfUw==
h7FLQ+Vc+L/SZXzgRtR2cNlo5j3RjENTEEdyo84iTZX6f7S4s2tZemKrPjEDJXth
let identity = function <T>(x: T): T {
// ...
};
let reverse = function <U>(y: U): U {
// ...
};
identity = reverse; // OK, because (x: any) => any matches (y: any) => any