TypeScript报错:类型'S'不满足'JSONSchema'约束,求解决方案
解决Type 'S' does not satisfy the constraint 'JSONSchema'错误
问题重现
你定义的TypeScript类型代码如下:
import type { APIGatewayProxyEvent, APIGatewayProxyResult, Handler } from 'aws-lambda' import type { FromSchema } from 'json-schema-to-ts' export type ValidatedAPIGatewayProxyEvent<S> = Omit<APIGatewayProxyEvent,'body'> & { body: FromSchema<S> } export type ValidatedEventAPIGatewayProxyEvent<S> = Handler<ValidatedAPIGatewayProxyEvent<S>,APIGatewayProxyResult> export const formatJSONResponse = ( statusCode: number, response: Record<string, unknown> ) => { return { statusCode: statusCode, body: JSON.stringify(response, null, 2) } }
编译时触发错误:
Type 'S' does not satisfy the constraint 'JSONSchema'. Type 'S' is not assignable to type '{ readonly type?: ReadonlyDeep<JSONSchema6TypeName | JSONSchema6TypeName[] | undefined>; readonly const?: ReadonlyDeep<unknown> | undefined; ... 35 more ...; readonly format?: ReadonlyDeep<...>; }'. 8 export type ValidatedAPIGatewayProxyEvent<S> = Omit<APIGatewayProxyEvent,'body'> & { body: FromSchema<S> }
错误原因
json-schema-to-ts库的FromSchema类型要求传入的泛型参数必须是合法的JSONSchema类型,但你定义的两个泛型类型中,S没有添加任何类型约束,TypeScript无法确认S符合JSONSchema的结构要求,因此抛出约束不满足的错误。
修复步骤
- 从
json-schema-to-ts导入JSONSchema类型 - 为泛型参数
S添加extends JSONSchema的约束,明确限定S必须是合法的JSONSchema结构
修复后的完整代码
import type { APIGatewayProxyEvent, APIGatewayProxyResult, Handler } from 'aws-lambda' // 新增导入JSONSchema类型 import type { FromSchema, JSONSchema } from 'json-schema-to-ts' // 为S添加extends JSONSchema约束 export type ValidatedAPIGatewayProxyEvent<S extends JSONSchema> = Omit<APIGatewayProxyEvent,'body'> & { body: FromSchema<S> } // 同样给这里的S添加约束 export type ValidatedEventAPIGatewayProxyEvent<S extends JSONSchema> = Handler<ValidatedAPIGatewayProxyEvent<S>,APIGatewayProxyResult> export const formatJSONResponse = ( statusCode: number, response: Record<string, unknown> ) => { return { statusCode: statusCode, body: JSON.stringify(response, null, 2) } }
这样修改后,TypeScript就能确认S是符合要求的JSONSchema类型,错误会被消除。
内容的提问来源于stack exchange,提问作者Heisenberg
相关产品推荐
相关产品推荐

