like this , You need to get the padding value of the incoming parameter , But it's not sure if elestyle was passed in , It is more uncertain whether other properties in elestyle are passed in , At present, ternary expression is used to judge , But it's still a bit cumbersome ...
data: {
show: true,
//可能传入的参数
eleStyle: {
//以下某一参数均有可能不传
width: 100,
height: 100,
padding: 20,
}
}
let padding = eleStyle && eleStyle.padding ? eleStyle.padding : 10
//当eleStyle.padding为0时, 所得到的padding值仍为默认, 所以可能应该是下面这种:
let padding = eleStyle && eleStyle.padding !== undefined ? eleStyle.padding : 10
If the required parameters are taken from deeper objects , That is also very bloated , So please ask if there is any good way to solve this problem ...
let padding = 'eleStyle.padding'.split('.').reduce((res,key)=>{return res != null ? res[key] : null},data)
padding = padding != null ? padding : 10;
30 seconds of code is a very elegant way to write, you can refer to it. The internal implementation of other practices may be different, but the concept is very similar.
const get = (from, ...selectors) =>
[...selectors].map(s =>
s
.replace(/\[([^\[\]]*)\]/g, '.$1.')
.split('.')
.filter(t => t !== '')
.reduce((prev, cur) => prev && prev[cur], from)
);
JS is really not a good solution. Ts3.7 provides a solution to deal with your needs
interface EleStyle{
width?:Number,
height?:Number,
padding?:Number
}
interface Data {
show:Boolean,
eleStyle?:EleStyle
}
let data:Data = {
show:true,
eleStyle:{
width: 100,
height: 100
}
}
console.log(data.eleStyle?.padding);
After looking at the document, I don't know how reduce works here