#Overriding primitive type instance methods

10 messages · Page 1 of 1 (latest)

tepid kiln
#

Hey :)

I want to simply override the type that's returned by my custom bigints' .toString() method, so it:
a) does not allow a radix
b) returns my custom string type

Setup:

type MarkedBigInt<M extends symbol> = bigint & { readonly m: M } & { toString(): MarkedString<M>; };
type MarkedString<M extends symbol> = string & { readonly m: M };

Usage:

declare const brand: unique symbol;

type Assert<T extends true> = T
type IsMarkedString<V> = V extends MarkedString<typeof brand> ? true : false;

const string0 = "1234" as MarkedString<typeof brand>;
type assert_working = Assert<IsMarkedString<typeof string0>>;

const id = 1234n as MarkedBigInt<typeof brand>;

const string1 = id.toString();
type test = Assert<IsMarkedString<typeof string1>>;
stiff moatBOT
#
daenamnu#0

Preview:```ts
type MarkedBigInt<M extends symbol> = bigint & {
readonly m: M
} & {toString(radix?: number): MarkedString<M>}
type MarkedString<M extends symbol> = string & {
readonly m: M
}

declare const brand: unique symbol

type Assert<T extends true> = T
type IsMarkedString<V> = V extends MarkedString<
typeof brand

? true
: false
...```

prime dome
#

i think you're just adding an overload of toString when you do that. if you hover over id.toString you can see that

#

you could Omit the toString from bigint first, but then your type is no longer a subtype of bigint:

stiff moatBOT
#
mkantor#0

Preview:```ts
type MarkedBigInt<M extends symbol> = Omit<
bigint,
"toString"

& {readonly m: M} & {
toString(radix?: number): MarkedString<M>
}
type MarkedString<M extends symbol> = string & {
readonly m: M
}
...```

prime dome
#

hah okay i have a better option actually

#

since overload signatures have an order and the first match is chosen at call sites, you can just rearrange your intersections:

stiff moatBOT
#
mkantor#0

Preview:ts type MarkedBigInt<M extends symbol> = { toString(radix?: number): MarkedString<M> } & bigint & {readonly m: M} type MarkedString<M extends symbol> = string & { readonly m: M } ...

prime dome
#

it's stupid, but that works

tepid kiln
#

Wait what. That's actually brilliant. I tried excluding the method from BigInt and it drove me crazy. tysm :p