TypeScript 中的':' 和'?:'的区别

在rect中, 有下面的代码: 
 
export type ReactComponentLike =
    | string
    | ((props: any, context?: any) => any)
    | (new (props: any, context?: any) => any);
 
props: any, 使用的是: 
context?:any , 却使用的是?: 
 
这两个符号有什么区别呢?
 
:这两个都表示参数的类型, 不同的是, 一个参数构造函数必须有的, 而另外一个, 是可选的.
 
看一下下面的代码:
 
//sharp.ts

interface Shape {
name: string;
width: number;
height: number;
color?: string;
}

function area(shape : Shape) {
var area = shape.width * shape.height;
return "I'm " + shape.name + " with area " + area + " cm squared";
}

console.log( area( {name: "rectangle", width: 30, height: 15} ) );
console.log( area( {name: "square", width: 30, height: 30, color: "blue"} ) );

 

posted @ 2020-07-21 19:31  Montai  阅读(4869)  评论(0编辑  收藏  举报