Как заставить непрозрачный тип предотвратить прием примитивного типа, с помощью которого он был создан? - PullRequest
0 голосов
/ 06 марта 2020

Учитывая

type Opaque<K, T> = T & { __TYPE__: K };
type UserId = Opaque<'UserId', string>;

const stringUserId: string = 'someId';
const userId: UserId = 'someId' as UserId;

const expectOpaqueType = (userId: UserId): void() => {/*nothing*/}
expectOpaqueType(stringUserId); // tsc will fail it

const expectStringType = (userId: string): void() => {/*nothing*/}
expectStringType(userId); // tsc will not fail it

Почему? Почему это не терпит неудачу и как заставить это потерпеть неудачу?

...