typescript - 僅對介面的單一屬性使用 as const
我有這個
interface MyType {id: string; label: string };
const t = [
{id: 'a' as const, label: 'A'},
{id: 'b' as const, label: 'B'}
] satisfies Array<MyType>;
這樣我以後就可以做
type Ids = (typeof t)[number]['id'];
所以 Ids 將會是 'a' | 'b';
這個方法運作良好。但我希望以一種不需要在每個 id 中都定義為 const 的方式來做。此外,'label' 應該是可變的,所以
const t = [
{id: 'a', label: 'A'},
{id: 'b', label: 'B'}
] as const satisfies Array<MyType>;
對我來說不是解決方法。
我該怎麼做?
答案#1
你可以透過一個使用兩個泛型參數的輔助函數來做到這一點,如下所示:
interface MyType {
id: string;
label: string;
}
const createArray = <
U extends string,
T extends ({ [K in Extract<keyof MyType, "id">]: U } & Omit<MyType, "id">)[],
>(
arr: T,
) => arr;
const t = createArray([
{ id: "a", label: "A" },
{ id: "b", label: "B" },
]);
type Ids = (typeof t)[number]["id"];
// ^? type Ids = "a" | "b"
TypeScript 遊樂場
