英文:
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 };
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论