Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

记录一个TS中的小坑 #10

Open
li-jia-nan opened this issue Oct 15, 2022 · 1 comment
Open

记录一个TS中的小坑 #10

li-jia-nan opened this issue Oct 15, 2022 · 1 comment

Comments

@li-jia-nan
Copy link
Owner

在渲染列表的时候,很多场景中都需要key这个属性,这个属性一般是后端给的,但是上次我发现后端给的数据出现了问题,于是就打算自己加一个key:

  • 在js中是这么写的:
export const addKey = list => {
    return list.map(item => ({ ...item, key: Symbol() }));
};
  • 在ts中是这么写的:
export const addKey = <T>(list: T[]): T[] => {
    return list.map((item: T) => ({ ...item, key: Symbol() }));
};
  • 此时还是没有问题的,于是我把文件后缀改成了tsx:
export const addKey = <T>(list: T[]): T[] => {
    return list.map((item: T) => ({ ...item, key: Symbol() }));
};

在编辑器中出现了报错:

aaaa.png

报错原因:

这里的原因是,在tsx文件中,编辑器把尖括号当成html标签处理了,所以,为了告诉编辑器这不是一个html标签,我们需要对代码稍微做出一些调整:

方法一:在泛型后面加上一个逗号,即可解决报错

export const addKey = <T,>(list: T[]): T[] => {
    return list.map((item: T) => ({ ...item, key: Symbol() }));
};

上面的方法虽然简单有效,也解决了报错,但是不够优雅

方法二:用 extends + 空对象 解决报错

export const addKey = <T extends {}>(list: T[]): T[] => {
    return list.map((item: T) => ({ ...item, key: Symbol() }));
};

上面的方法虽然优雅的解决了报错,但是不够专业

方法三:用 extends + Record 解决报错

export const addKey = <T extends Record<string, any>>(list: T[]): T[] => {
    return list.map((item: T) => ({ ...item, key: Symbol() }));
};

上面三种方法都是简单有效的解决方案,看你喜欢,任选其一即可。

@Wxh16144
Copy link

Wxh16144 commented Jul 6, 2023

再补充一个方法, 我们可以不用箭头函数, 用普通函数 😂

export function addKey<T>(list: T[]): T[] {
  return list.map((item) => ({ ...item, key: Symbol() }));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants