这是我的代码
interface page {
type: '1' | '2'
}
interface Menu {
id: string,
title: string,
page: page,
}
export const menus: Menu[] = [
{
id: 'externalCustomer',
title: 'title',
page: { type: '1' }
}
]
有没有办法使id为const?菜单类型是Menu[],而菜单id是const,就像
interface page {
type: '1' | '2'
}
interface Menu<T> {
id: T[number].id,
title: string,
page: page,
}
export const menus: Menu<typeof menus>[] = [
{
id: 'externalCustomer',
title: 'title',
page: { type: '1' }
}
]
我试着这样写
const menus = [
{
id: 'externalCustomer',
title: 'title',
page: { type: '1' }
}
] as const
但是这样的话,页面的类型就会丢失
使用联合类型可能会完成这项工作。
interface page {
type: '1' | '2'
}
interface Menu<I> {
id: I,
title: string,
page: page,
}
const menus: Menu<'externalCustomer' | 'test'>[] = [
{
id: 'externalCustomer',
title: 'title',
page: { type: '1' }
}, {
id: 'test',
title: 'title',
page: { type: '1' }
}, {
id: 'aaa', //type error
title: 'title',
page: { type: '1' }
},
];