typescript 打字稿鸭打字

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 打字稿鸭打字相关的知识,希望对你有一定的参考价值。

interface IItem 
{
    id: number,
    title: string
};
function print(item: IItem) 
{
    console.log(item.id + " > " + item.title);
}
var i : IItem = {
    id: 10,
    title : "ABC"
};
//Ok - As it implements IItem
print(i);

//Ok - As it implicitly implements IItem
print({ id: 11, title: "XYZ"});

interface IProduct
{
    id: number,
    title: string,
    author: string
};

var book: IProduct = {
    id: 1,
    title: "C# in Depth",
    author: "Jon Skeet"
};

//Ok - Even though book implements IProduct and not the IItem
//It has two properties "id" and "title" 
//which is actually the print function is interested in
print(book);

print({
    id: 2,
    title: 'fuck',
    author: 'leo'
})

var x = {
    id: 3,
    title: "fuck again",
    author: 'leo'
} 

print(x)

以上是关于typescript 打字稿鸭打字的主要内容,如果未能解决你的问题,请参考以下文章

typescript 打字稿泛型示例

typescript 打字稿工厂示例

typescript 打字稿纯函数示例

typescript 打字稿对象示例

typescript 打字稿类示例

typescript 打字稿索引签名示例