TypeScript Interface is confused?

How do I set the default value of a parameter when a function in

TypeScript describes a parameter through Interface?

interface Opts {
  method: string;
  header: object;
  body: object;
}

function request(url: string, opts: Opts) {
  // opts.methodopts.header
  // ...
}
May.31,2022

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}
  
}

Please note

there is a potential danger in the above answer: both assign and structure assignments can only be replaced by layer 1, and layer 2 attribute values cannot be compared.
as in the above code, it is assumed that the default defaultOpts.body = {avav _ 1jbv _ 2}, but in the parameter passed, props.body = {av _ 3}, then the merging value of the two does not have the attribute xxx.body.b.


  

is actually true. There is no so-called default value in interface, which is different from the attributes in react PropType or vue

.
Menu