1
SilentDepth 2022-07-20 11:56:11 +08:00 1
function concatHeaderAndData <H, D>(header: H, data: D) { /* ... */ }
|
2
AlphaTr 2022-07-20 12:59:30 +08:00 2
concatHeaderAndData<K extends string | number | symbol, T extends string | number | symbol, S extends Record<K, any>>(h: Record<K, T>, d: Array<S>): Array<Record<T, S[keyof S]>> 不知道是不是这个意思
|
3
particlec OP @AlphaTr @SilentDepth 谢谢,两个都可以都不会报错
|
4
yazoox 2022-07-20 13:50:33 +08:00
interface Header {
[key: string]: string | number; // or using 'any' as type directly } const concatHeaderAndData = (header: Header, data: Array<Header>) => { // } |
5
AlphaTr 2022-07-20 13:59:32 +08:00
更严谨可能是这样子, 能直接根据传参推断出返回值类型
type ReverseMap<T extends Record<keyof T, keyof any>> = { [P in T[keyof T]]: { [K in keyof T]: T[K] extends P ? K : never }[keyof T] } function concatHeaderAndData<K extends string | number | symbol, H extends Record<keyof H, K>, S extends Record<keyof H, keyof any>>(h: H, d: Array<S>): Array<{ [P in H[keyof H]]: S[ReverseMap<H>[P]] }> https://www.typescriptlang.org/play?#code/C4TwDgpgBA0hICYBqBDANgV2gXigbwCgooAzAezIC4oAiAIxQCcaioA3C6mgEwpYF8CBUJCgAlCGwiMAzhACyKMAB4AKlAgAPYBAB23GeIgBjMo27KA1vDIkoqgDRRrIW1BS6QAPi9RchYmIAbQAFKABLXXsglzdVAF146gDA1KCYCKjYuwTqVXT4jW09AygwgH5YKGpdSWlWYn4Ymxz4gkECEgxdY2BwsijTHpRgAAkIFG5pAEF9ABERlGUMrR19QxlgRkiAcygAHyhdDABbOmkDqBkQM7I0J1GitdKJU3MrFqhRpxgvJwBlJ4lQyvMwWbJfJwQjzeLwACgAFtRvlBuNRpoxGCgQMp-l4AJTozHY5QpUKZL7NVx2UaJaj-IISKSyBRKZSjLyhRLtXwpRgQYAYRhRbjuQzdSy6MgAdyiKEMGKxOLJYUilIhtKSUAZTOkckUKg5XLa-C87SEQ2MI3Gkxm80WcLwKC4gHALQAZGTQnHQuABhP00fhOIJOrgARnDnqg3qg4dD-Hi+KAA |
6
particlec OP 补充了一些业务逻辑,然后发现上面定义的类型全部都会标红
const concatHeaderAndData = (header: any, data:any[]) => { return data.map((item) => { return Object.keys(item).reduce((newData, key) => { const newKey = header[key] || key; newData[newKey] = item[key]; return newData; }, {}); }); }; |
7
duan602728596 2022-07-20 16:01:04 +08:00 1
type Item = Record<string, string>;
const headers: Item = { a: 'sss', b: '京津冀' }; const data: Array<Item> = [ { a: '迭代', b: '迭代' }, { a: '测试', b: '测试' }, { a: '哦哦', b: '偶偶' } ]; const concatHeaderAndData = (header: Item, data: Array<Item>): Array<Item> => { return data.map((item: Item): Item => { return Object.keys(item).reduce((newData: Item, key: string): Item => { const newKey = header[key] || key; newData[newKey] = item[key]; return newData; }, {}); }); }; |
8
Bingchunmoli 2022-07-20 16:25:21 +08:00 via Android
遇见报错无脑 any ,,
|
9
particlec OP @duan602728596 可以了,加逻辑后不报错,niub
|
10
chenzhe 2022-07-21 02:04:10 +08:00 via iPhone
有个网站可以吧数据结构复制进去然后自动生成类型,忘记网址了。你可以搜一搜 顺便楼内等大佬解答 哈哈哈
|