设置TypeScript的接口属性为可选值。

接口是TypeScript的核心之一,作用是对值所具有的结构进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类型化”。接口的作用就是为这些类型命名和对代码或第三方代码定义契约。而接口里的属性很多时候并不一定都要传,更多是可选的。大部分情况下传入对象的只有部分的属性。但是这样直接传会报错,所以TypeScript可以通过在参数后跟上?来表示可选。
例如

    interface temp{
    
    
        name?: string;
        age?: number;
        height?:number
    } 
	  const newTest = reactive({
    
     name: "test", age: 10});
    function test(config: temp): {
    
     name: string; age: number,height:number } {
    
    
        if (config.name) {
    
    
            newTest .name= config.color;
        }
        if (config.age) {
    
    
            newTest .age= config.age;
        }
        return newTest ;
    }
    let mySquare = test({
    
     name: "temp" });

猜你喜欢

转载自blog.csdn.net/weixin_45807026/article/details/128610098