-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformattable-string.ts
More file actions
55 lines (45 loc) · 1.46 KB
/
formattable-string.ts
File metadata and controls
55 lines (45 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import type { TelegramMessageEntity } from "@gramio/types";
/** Type which contains a string or has the ability to result in a string object */
export type Stringable =
| string
| {
toString(): string;
};
/** Class-helper for work with formattable [entities](https://core.telegram.org/bots/api#messageentity) */
export class FormattableString {
/** Text of FormattableString (auto covert to it if entities is unsupported)*/
text: string;
/** Entities of FormattableString */
entities: TelegramMessageEntity[];
/** Create new FormattableString */
constructor(text: string, entities: TelegramMessageEntity[]) {
this.text = text;
this.entities = entities;
}
/** Create new FormattableString */
static from(text: string, entities: TelegramMessageEntity[]) {
return new FormattableString(text, entities);
}
toString() {
return this.text;
}
toJSON() {
return this.text;
}
// ![INFO] - https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-3.html#instanceof-narrowing-through-symbolhasinstance
static [Symbol.hasInstance](value: unknown): value is FormattableString {
return (
!!value &&
typeof value === "object" &&
"text" in value &&
"entities" in value
);
}
}
export function getFormattable(str: Stringable | undefined | null) {
if (str instanceof FormattableString) return str;
if (str == null || str === undefined) {
return new FormattableString("", []);
}
return new FormattableString(str.toString(), []);
}