TypeScript中函数通过Interface来描述参数时,如何设置参数的默认值?
interface Opts {
method: string;
header: object;
body: object;
}
function request(url: string, opts: Opts) {
// opts.method,opts.header等参数如何设置默认值?
// 省略代码...
}
interface Opts {
method: string;
header: object;
body: object;
}
function request(url: string, opts: Opts) {
// opts.method,opts.header等参数如何设置默认值?
// 省略代码...
}
interface Opts {
method: string;
header: object;
body: object;
}
const defaultOpts:Opts = {
method='get',
header= {},
body={}
}
function request(url: string, opts: Opts) {
opts = Object.assign(defaultOpts,opts)
//或者
opts = {...defaultOpts,...opts}
}
上面答案存在一个潜在隐患:无论 assign还是结构赋值,都只能进行第1层的替换,无法对比第2层属性值。
像上面代码中,假设默认 defaultOpts.body = {a:1,b:2},但是传递过来的参数中,props.body = {a:3},那么2者合并之后的值是不存在 xxx.body.b 这个属性的。