Restrict the inferred type from a Record to its corresponding key

I am trying to create a function that accepts either keys of an object, or an object referencing both the key and a given value.

When providing an object, I would like to infer the type of the value from the given key.

Currently I’m almost there, the only issue is with the last line: I can provide a combination of any key and any accepted type, whereas I would like to be able to provide only the corresponding type.

Here is the code :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { HttpContextToken } from '@angular/common/http';
const tokens = {
omitBaseUrl: new HttpContextToken(() => true),
test: new HttpContextToken(() => ({ some: 'value' })),
} as const;
type Tokens = typeof tokens;
type ContextParameter =
{ [K in keyof Tokens]: HttpContextToken<any> } extends Record<infer KK extends keyof Tokens, HttpContextToken<any>>
? Tokens[KK] extends HttpContextToken<infer X>
? KK | { context: KK; value: X }
: never
: never;
export function withContext(...contexts: ContextParameter[]) {}
withContext('omitBaseUrl');
withContext('test');
withContext({ context: 'omitBaseUrl', value: true });
withContext({ context: 'test', value: { some: '' } });
withContext('xxx');
withContext(12);
withContext({ context: 'omitBaseUrl', value: 12 });
withContext({ context: 'omitBaseUrl', value: { some: '' } });
</code>
<code>import { HttpContextToken } from '@angular/common/http'; const tokens = { omitBaseUrl: new HttpContextToken(() => true), test: new HttpContextToken(() => ({ some: 'value' })), } as const; type Tokens = typeof tokens; type ContextParameter = { [K in keyof Tokens]: HttpContextToken<any> } extends Record<infer KK extends keyof Tokens, HttpContextToken<any>> ? Tokens[KK] extends HttpContextToken<infer X> ? KK | { context: KK; value: X } : never : never; export function withContext(...contexts: ContextParameter[]) {} withContext('omitBaseUrl'); withContext('test'); withContext({ context: 'omitBaseUrl', value: true }); withContext({ context: 'test', value: { some: '' } }); withContext('xxx'); withContext(12); withContext({ context: 'omitBaseUrl', value: 12 }); withContext({ context: 'omitBaseUrl', value: { some: '' } }); </code>
import { HttpContextToken } from '@angular/common/http';

const tokens = {
  omitBaseUrl: new HttpContextToken(() => true),
  test: new HttpContextToken(() => ({ some: 'value' })),
} as const;
type Tokens = typeof tokens;

type ContextParameter =
  { [K in keyof Tokens]: HttpContextToken<any> } extends Record<infer KK extends keyof Tokens, HttpContextToken<any>>
    ? Tokens[KK] extends HttpContextToken<infer X>
      ? KK | { context: KK; value: X }
      : never
    : never;

export function withContext(...contexts: ContextParameter[]) {}

withContext('omitBaseUrl');
withContext('test');
withContext({ context: 'omitBaseUrl', value: true });
withContext({ context: 'test', value: { some: '' } });

withContext('xxx');
withContext(12);
withContext({ context: 'omitBaseUrl', value: 12 });
withContext({ context: 'omitBaseUrl', value: { some: '' } });

StackBlitz

2

The Record<K, V> utility type doesn’t track individual key-value type mappings. Instead it associates all keys with the union of values. If you try to infer {a: string, b: number} to Record<infer K, infer V> you’ll get Record<"a" | "b", string | number> and thus {a: string | number, b: string | number}. Similarly if you index into an object type with its full union of keys, you’ll get its full union of value types. So {a: string, b: number}["a" | "b"] is just string | number. Your ContextParameter definition does both of these, hopelessly mixing all property value types together.

Instead, you should consider using a distributive object type as coined in microsoft/TypeScript#47109. Instead of inferring, just map over every property key K of Tokens and do your analysis there. Then when you’re done, index into that mapped type to get the union of analyzed types. This way, K will always be a single key and your computed type won’t mix them:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>type ContextParameter =
{ [K in keyof Tokens]: Tokens[K] extends HttpContextToken<infer X>
? K | { context: K; value: X }
: never }[keyof Tokens]
/* type ContextParameter = "omitBaseUrl" | "test" | {
context: "omitBaseUrl";
value: boolean;
} | {
context: "test";
value: {
some: string;
};
} */
</code>
<code>type ContextParameter = { [K in keyof Tokens]: Tokens[K] extends HttpContextToken<infer X> ? K | { context: K; value: X } : never }[keyof Tokens] /* type ContextParameter = "omitBaseUrl" | "test" | { context: "omitBaseUrl"; value: boolean; } | { context: "test"; value: { some: string; }; } */ </code>
type ContextParameter =
  { [K in keyof Tokens]: Tokens[K] extends HttpContextToken<infer X>
    ? K | { context: K; value: X }
    : never }[keyof Tokens]

/* type ContextParameter = "omitBaseUrl" | "test" | {
    context: "omitBaseUrl";
    value: boolean;
} | {
    context: "test";
    value: {
        some: string;
    };
} */

That looks like what you want; the context/value pairs are in separate union members as desired.

Playground link to code

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật