Skip to content

Commit 5198321

Browse files
Myesteryvigoo
andauthored
sdks/ts: replace any with proper types in SDK core (#2857)
Replace `any` types with `unknown`, generics, and proper type constraints across the SDK. Uses Reflect.construct for safe instantiation, Object.assign for typed function objects, and generic wrappers for deserialize functions. Co-authored-by: Daniel Vigovszky <daniel.vigovszky@gmail.com>
1 parent 39291e7 commit 5198321

File tree

7 files changed

+28
-25
lines changed

7 files changed

+28
-25
lines changed

sdks/ts/packages/golem-ts-sdk/src/baseAgent.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,11 @@ export class BaseAgent {
109109
*/
110110
async loadSnapshot(bytes: Uint8Array): Promise<void> {
111111
const text = new TextDecoder().decode(bytes);
112-
const state = JSON.parse(text);
112+
const state = JSON.parse(text) as Partial<this>;
113113

114114
for (const [k, v] of Object.entries(state)) {
115115
if (k === 'cachedAgentType' || k === 'agentClassName') continue;
116-
(this as any)[k] = v;
116+
this[k as keyof this] = v;
117117
}
118118
}
119119

@@ -230,15 +230,17 @@ export class BaseAgent {
230230
*
231231
* ```
232232
*/
233+
type MethodKeys<T> = {
234+
[K in keyof T]-?: T[K] extends (...args: never[]) => unknown ? K : never;
235+
}[keyof T];
236+
233237
export type Client<T> = {
234-
[K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K] extends (
235-
...args: infer A
236-
) => infer R
238+
[K in MethodKeys<T>]: T[K] extends (...args: infer A) => infer R
237239
? RemoteMethod<GetArgs<A>, Awaited<R>>
238240
: never;
239241
};
240242

241-
export type RemoteMethod<Args extends any[], R> = {
243+
export type RemoteMethod<Args extends unknown[], R> = {
242244
(...args: Args): Promise<R>;
243245
trigger: (...args: Args) => void;
244246
schedule: (ts: Datetime, ...args: Args) => void;
@@ -264,8 +266,8 @@ type GetArgs<T extends readonly unknown[]> =
264266
type IsOptional<T extends readonly unknown[], K extends keyof T> =
265267
{} extends Pick<T, K> ? true : false;
266268

267-
type AllOptional<T extends readonly unknown[], I extends any[] = []> = T extends readonly [
268-
any,
269+
type AllOptional<T extends readonly unknown[], I extends unknown[] = []> = T extends readonly [
270+
unknown,
269271
...infer R,
270272
]
271273
? IsOptional<T, I['length']> extends true

sdks/ts/packages/golem-ts-sdk/src/host/result.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -320,25 +320,25 @@ function flatten<T, E, E2>(this: Result<Result<T, E>, E2>): Result<T, E | E2> {
320320
else return this.val;
321321
}
322322

323-
function assertErrorInstanceOf<T, C extends abstract new (..._: any) => any>(
323+
function assertErrorInstanceOf<T, C extends abstract new (..._: unknown[]) => unknown>(
324324
this: Result.Ok<T>,
325325
constructor: C,
326326
): Result.Ok<T>;
327-
function assertErrorInstanceOf<E, C extends abstract new (..._: any) => any>(
327+
function assertErrorInstanceOf<E, C extends abstract new (..._: unknown[]) => unknown>(
328328
this: Result.Err<E>,
329329
constructor: C,
330330
): Result.Err<E & InstanceType<C>>;
331-
function assertErrorInstanceOf<T, E, C extends abstract new (..._: any) => any>(
331+
function assertErrorInstanceOf<T, E, C extends abstract new (..._: unknown[]) => unknown>(
332332
this: Result<T, E>,
333333
constructor: C,
334334
): Result<T, E & InstanceType<C>>;
335-
function assertErrorInstanceOf<T, E, C extends abstract new (..._: any) => any>(
335+
function assertErrorInstanceOf<T, E, C extends abstract new (..._: unknown[]) => unknown>(
336336
this: Result<T, E>,
337337
constructor: C,
338338
): Result<T, E & InstanceType<C>> {
339339
if (this.isOk()) return this;
340340

341-
if (this.val instanceof constructor) return this as any;
341+
if (this.val instanceof constructor) return this as Result<T, E & InstanceType<C>>;
342342

343343
throw new TypeError(`Assertion failed: Expected error to be an instance of ${constructor.name}.`);
344344
}

sdks/ts/packages/golem-ts-sdk/src/host/transaction.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,6 @@ export function fallibleTransaction<Out, Err>(
233233
* ```
234234
*
235235
*/
236-
export type OperationErrors<T extends Operation<any, any, any>[]> = {
237-
[K in keyof T]: T[K] extends Operation<any, any, infer Err> ? Err : never;
236+
export type OperationErrors<T extends Operation<unknown, unknown, unknown>[]> = {
237+
[K in keyof T]: T[K] extends Operation<unknown, unknown, infer Err> ? Err : never;
238238
}[number];

sdks/ts/packages/golem-ts-sdk/src/internal/mapping/types/handlers.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ const handlers: { [K in TsType['kind']]: Handler<K> } = {
7070
config: unsupported('Config'),
7171
};
7272

73-
function unsupported(kind: string): Handler<any> {
73+
function unsupported<K extends TsType['kind']>(kind: string): Handler<K> {
7474
return ({ scopeName, parameterInScope }) =>
7575
Either.left(
7676
`Unsupported type \`${kind}\`` +
@@ -79,7 +79,7 @@ function unsupported(kind: string): Handler<any> {
7979
);
8080
}
8181

82-
function unsupportedWithHint(kind: string, hint: string): Handler<any> {
82+
function unsupportedWithHint<K extends TsType['kind']>(kind: string, hint: string): Handler<K> {
8383
return ({ scopeName, parameterInScope }) =>
8484
Either.left(
8585
`Unsupported type \`${kind}\`${scopeName ? ` in ${scopeName}` : ''}` +

sdks/ts/packages/golem-ts-sdk/src/internal/mapping/types/witTypeBuilder.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export class WitTypeBuilder {
4949
}
5050

5151
private convert(typ: AnalysedType): WitTypeNode {
52+
let kind = typ.kind;
5253
switch (typ.kind) {
5354
case 'variant': {
5455
const cases: [string, NodeIndex | undefined][] = typ.value.cases.map(
@@ -127,7 +128,7 @@ export class WitTypeBuilder {
127128
}
128129

129130
default:
130-
throw new Error(`Unhandled AnalysedType kind: ${(typ as any).kind}`);
131+
throw new Error(`Unhandled AnalysedType kind: ${kind}`);
131132
}
132133
}
133134
}

sdks/ts/packages/golem-ts-sdk/src/internal/mapping/values/errors.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import * as util from 'node:util';
1616
import { NameOptionTypePair } from '../types/analysedType';
1717

1818
// type mismatch in tsValue when converting from TS to WIT
19-
export function typeMismatchInSerialize(tsValue: any, expectedType: string): string {
19+
export function typeMismatchInSerialize(tsValue: unknown, expectedType: string): string {
2020
return `Type mismatch. Expected type \`${safeDisplay(expectedType)}\`, got \`${safeDisplay(tsValue)}\``;
2121
}
2222

@@ -30,23 +30,23 @@ export function typeMismatchInDeserialize(nodeTag: string, expectedType: string)
3030
}
3131

3232
// Missing keys in tsValue when converting from TS to WIT
33-
export function missingObjectKey(key: string, tsValue: any): string {
33+
export function missingObjectKey(key: string, tsValue: unknown): string {
3434
return `Missing key '${key}' in ${safeDisplay(tsValue)}`;
3535
}
3636

3737
// tsValue does not match any of the union types when converting from TS to WIT
38-
export function unionTypeMatchError(unionTypes: NameOptionTypePair[], tsValue: any): string {
38+
export function unionTypeMatchError(unionTypes: NameOptionTypePair[], tsValue: unknown): string {
3939
const types = unionTypes.map((t) => t.name);
4040
return `Value '${safeDisplay(tsValue)}' does not match any of the union types: ${types.join(', ')}`;
4141
}
4242

43-
export function enumMismatchInSerialize(enumValues: string[], tsValue: any): string {
43+
export function enumMismatchInSerialize(enumValues: string[], tsValue: unknown): string {
4444
return `Value '${safeDisplay(tsValue)}' does not match any of the enum values: ${enumValues.join(', ')}`;
4545
}
4646

4747
// unhandled type of tsValue when converting from TS to WIT
4848
export function unhandledTypeError(
49-
tsValue: any,
49+
tsValue: unknown,
5050
typeName: string | undefined,
5151
message: string | undefined,
5252
): string {
@@ -57,6 +57,6 @@ export function unhandledTypeError(
5757
return error + (message ? `${message}` : '');
5858
}
5959

60-
export function safeDisplay(tsValue: any): string {
60+
export function safeDisplay(tsValue: unknown): string {
6161
return util.format(tsValue);
6262
}

sdks/ts/packages/golem-ts-sdk/src/webhook.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ export class WebhookHandler implements PromiseLike<WebhookRequestPayload> {
4545

4646
then<TResult1 = WebhookRequestPayload, TResult2 = never>(
4747
onfulfilled?: ((value: WebhookRequestPayload) => TResult1 | PromiseLike<TResult1>) | null,
48-
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,
48+
onrejected?: ((_reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
4949
): Promise<TResult1 | TResult2> {
5050
return this.wait().then(onfulfilled, onrejected);
5151
}

0 commit comments

Comments
 (0)