2020/3/12 TSUserIdPostId

kansai.ts


TypeScript




stringnumber
type UserId = number;
type PostId = number;
const userId: UserId = 888;
const postId: PostId = 24;
const register = (userId: UserId, postId: PostId) => {...}
register(postId, userId) // NoError!!
string
Literal typemrsekut
mrsekut


0
userIdgenreIdtagId
number
updatedAt, createdAt
JPYEUR


branded types使
TypeScript使
TSmrsekut


type UserId = number & { "UserId": never };
type PostId = number & { "PostId": never };
UserId PostId


GenericBranded便
type Branded<Type, Data extends string> = Type & { [key in Data]: never };
使
type UserId = Branded<number, "UserId">;
const makeUserId = (n: number) => n as UserId;
APIuserId userId()


//
type Branded<Type, Data extends string> = Type & { [key in Data]: never };
type UserId = Branded<number, "UserId">;
type PostId = Branded<number, "PostId">;
// id
export const makeUserId = (n: number) => n as UserId;
export const makePostId = (n: number) => n as PostId;
// id
const userId = makeUserId(888);
const postId = makePostId(24);
const register = (userId: UserId, postId: PostId) => {};
register(postId, userId); // error!

// id
const userId = makeUserId(888);
const postId = 24; // makePostId
register(userId, postId); // error!


userIdpostId
const userId = makeUserId(888) as PostId; // error!




VSCodehover
type
id
const userId = makeUserId(888);
const a = userId + userId // number


TS
type literal type ref
Enums ref
number使
Flavor使
BrandedTypesGraphQL


data PhantomType x a = PhantomType a
x a body x 使
x
data PostId
data UserId
type UID = PhantomType UserId Int
type PID = PhantomType PostId Int
UID PID body PhantomType Int
UID PID


TypeScript
type Id<T extends string> = number;
type UserId = Id<"UserId">;
type PostId = Id<"PostId">;
const userId = 24 as UserId; // number
const postId = 24 as PostId; // number
const register = (userId: UserId, postId: PostId) => {};
register(userId, postId); // NoError!!
TypeScript
type newtype