如何从接口外部访问变量。在这个Example2代码中,我期望得到与Example1相同的结果。建议我怎么做?

// Example 1
class Sample1{
    data?:string;
}

const d1 = new Sample1()
d1.data = "hai"
console.log(d1)// Result Sample1 { data: 'hai' }

// Example 2
interface Sample2{
    dat1?:any;
}

class Sample3 implements Sample2{
    dat1:any
   constructor(dat1:Sample2){
        this.dat1 = dat1
    }
}

const d2 = new Sample3({dat1:"hai"})
console.log(d2) // Sample3 { dat1: { dat1: 'hai' } }

最佳答案

编辑

使用价差运算符:

// Example 2
interface Sample2{
    dat1?:any;
}

class Sample3 implements Sample2{
    dat1:any
   constructor(dat:Sample2){
        this.dat1 = {...dat}
    }
}

const d2 = new Sample3({dat1:"hai"})

关于javascript - 如何从接口(interface)外部访问变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58659380/

10-10 00:27