开始
TypeScript 结构类型系统的基本规则是,如果 y
至少具有与 x
相同的成员,则 x
与 y
兼容。例如,考虑以下代码,其中涉及一个名为 Pet
的接口,该接口具有 name
属性:
The basic rule for TypeScript's structural type system is that x
is compatible with y
if y
has at least the same members as x
. For example consider the following code involving an interface named Pet
which has a name
property:
interface Pet {
name: string;
}
let pet: Pet;
// dog's inferred type is { name: string; owner: string; }
let dog = { name: "Lassie", owner: "Rudd Weatherwax" };
pet = dog;
BmVZlHIQt9JumkDauCVkk5WxmYAIq0K0RrjN6PWN9Hf7W9TinkQLEFF4VQpOTSo2WrfCieQfmzL/1h7b3BlLLUIQ11/volMedk+w8QKKyq8VIo34JcmfwhQe2i/2v5Ihsfc5TWMR5mt9Hl7VuYFLTataaqTi3BEaql0r48IUZG+XoCsDdQ4qZ+IVkQms1eN6/wBQ9CA8f1VSa73qUYMoLi0HMyMH6FAABVkUcUcvNMqtyTor2nYJeBedVeQtzBsOgKCynLjLoHg0jjpJ2k+3hdIaGoV0/AtFpseUwnQcuuCGd8QAYP3tPpXRJGydCWnBQyaTPkMJcoRwC2oTzIlaZkc+dEhfB+s9E9wOdP07UZOoNjm2S3VMP5pTPE1tfrdpG0uxWBkLu59mP0bC5IxoEvJT2wtYXLjvTKgxTdEe2LWKSyOpwFJqXX9sGMfV2yfOAwpuoTa4egPvsS+pW65kizUlKzkh1YpY9zdM/ejqP0BJf8qlRBfaNROvKz696QV8a97s7lmMjjlWB6SizRg0fzhmqkrVvShivgS8oi8Bm7qEQJhiBLVgThPXMsse6POVn5f2ofO3CDV75s1x4IQPb9ZkYOesaF0hAFFO3oXP3zhKw3G9VDorGEBVXQGjj2LPnOH+hLpn0jajBif2dcRn7LQZThSCDw3ivF5ZKEyVEC75rKDtLpTxKNbhw9hI2w9zQBG5i0izPFsv1JkFTEX0WjOqwUCJUXg44qnsosdxen7pwOCclZO+PRXXodnJy8uQv+Yrk1mBGv+/PDviq0VA+cCh9qfgNoQdwGuzO/LLk7qSwXJ4J7r6Q4TQXp/6naxFSoDoG9JsQWtIUrQx44ajMv2HrzxN+5zbZ8Buk1Ggfk9Ka6KvLeAzQcBemsC+oT2uetK50DSKRYOtF5N6aN7QIA==
9JK03JMWhpjNRUsqSUm12BPgMaL4oQ6OH8xsEviAy12YSoO2apcdV4v76nO8kmcOjbSH+M08W9E9m9EzrkYSpwo477tOxob3kbiqm+qsrONfXZy1tcz+Df8C9qhqEnmOpGw6tYvm0BJmgRuBIHXwxQ3advVgHrVPc5PwGk9UC6LIY5tIhRb4+AUVE1femHr3ZfKuHRV8BvRH/B5ECS6Gdw==
interface Pet {
name: string;
}
let dog = { name: "Lassie", owner: "Rudd Weatherwax" };
function greet(pet: Pet) {
console.log("Hello, " + pet.name);
}
greet(dog); // OK
qDL+w2ddVc57/QL3Rt4bNROYymu1rhMzQz+CcvAZAGOMnwRS/Nwd4sRxRxRLc1az5/haXaLW/JDlR1EdmLrrc2WmGP5llbCio2mcTiUkf/KGOxlplTG60zXF/qh7CyPwzCyhe66JvFcnghOwvbqG1iYmqT9j+p1c1U8vNfqceYnV4AFYp7VRMdhR/j4eeFJOJOkznFYflTnWUnxkkPLhBq4GIQidNRDvENf5/pfwaqkZDyQ//02tXuUucaDdpAdRJboGRP9CbnCpwCo6ez0hjY45ewEP8l5JrGAimbgN47D4qyBFgKwKvDnnoh3pgCk2WZCSf8PUYp/WZecjXpUXOQKvoHVvOZP8OZzjXLysTQ4b5aQ0QGiLWQKGhigUFNb0C7GbAy84f1U5/JG3d7dg47xUYHV5FMNV0DbxWNgdwwOnzX+rugM1YWJklRdgf9OqqIcFbAwF0EeebeoCQaGzWKko90xyr08/qMSsz08OpPJeBM0LAfHVNlz1oWmjVAAWJOnyLkCllCIS4uOnjhP0HKzu+oUbmXenv6K+wtNLUOdyS3Cogr9xBDbIu8eTk+gdmae7TGT2iQqCoav9Nr7ZZg==
s7PRLUyrN5UaHhxhmY/c6QdfIDafGnTPMxjTkj7x2EiWJ7B2ayJnys+qQ783YmUVUp9V3D8sXvXHY/3p49IO3hTTuubVIvVOwtm+vnJadK/WSpnXZUPcL6unflYXnHP8uFwCP4ONuXy6/iaXmqb8PmhsWBZQ2H2O3StYgNBG+PQf19V3r+CFHIYhefB239kql6JTQJbsqEjNfi77XSgEvERSmAScUiOCEQoayy2vPftap1UECpLTeGc2oxuqxw+nDtaRYdJOtRsTtSx/IoiXRg==