函数参数解构与默认值在 TypeScript 中是如何工作的?

huangapple go评论47阅读模式
英文:

How destructuring function params with defaults work in ts?

问题

const test = ({
  foo = 'foo',
  bar = 'bar',
}: { foo?: string; bar?: string } = {}) => {
  return { foo, bar };
};
英文:
const test = ({ foo = 'foo', bar = 'bar' } = {}) => {
  return { foo, bar };
};

test(); // { foo: 'foo', bar: 'bar' }
test({}); // { foo: 'foo', bar: 'bar' }
test({ foo: 'cat' }); // { foo: 'cat', bar: 'bar' }

But if i rewrite it in TS

const test = ({
  foo = 'foo',
  bar = 'bar',
}: { foo: string; bar: string } = {}) => {
  return { foo, bar };
};

= {} will cause error because of type mismatch (but as we see in first example — there is no undefined params and should be no type mismatch).

How to rewrite JS example in TS properly?

答案1

得分: 0

以下是已翻译的代码部分:

try this in your ts file :

    const test = ({
      foo = 'foo',
      bar = 'bar',
    }: { foo?: string; bar?: string } = {}) => {
      return { foo, bar };
    };
英文:

try this in your ts file :

const test = ({
  foo = 'foo',
  bar = 'bar',
}: { foo?: string; bar?: string } = {}) => {
  return { foo, bar };
};

huangapple
  • 本文由 发表于 2023年2月8日 15:50:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定