Skip to content

Commit

Permalink
Enhance type safety in StructuredView ensuring that
Browse files Browse the repository at this point in the history
more specific TypeDefinitions lead to stricter and more accurate type
checks.

Signed-off-by: Ruby Quail <[email protected]>
  • Loading branch information
rubyquaildesign committed Jan 13, 2024
1 parent 277d506 commit 4d3a13c
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/buffer-views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ export function setStructuredView(data: any, views: TypedArrayOrViews): void {
}
}

export type StructuredView = ArrayBufferViews & {
export type StructuredView<ViewType extends TypeDefinition> = ArrayBufferViews & {
/**
* Sets the contents of the TypedArrays based on the data passed in
* Note: The data may be sparse
Expand Down Expand Up @@ -425,7 +425,7 @@ export type StructuredView = ArrayBufferViews & {
*
* @param data
*/
set(data: any): void;
set(data: ViewType extends StructDefinition ? Partial<Record<keyof ViewType['fields'],any>> : any): void;
}

/**
Expand All @@ -436,13 +436,13 @@ export type StructuredView = ArrayBufferViews & {
* @returns TypedArray views for the various named fields of the structure as well
* as a `set` function to make them easy to set, and the arrayBuffer
*/
export function makeStructuredView(varDef: VariableDefinition | StructDefinition, arrayBuffer?: ArrayBuffer, offset = 0): StructuredView {
export function makeStructuredView<InputType extends VariableDefinition | StructDefinition, ViewType extends TypeDefinition = InputType extends VariableDefinition ? InputType['typeDefinition'] : InputType>(varDef: InputType, arrayBuffer?: ArrayBuffer, offset = 0): StructuredView<ViewType> {
const asVarDef = varDef as VariableDefinition;
const typeDef = asVarDef.group === undefined ? varDef as StructDefinition : asVarDef.typeDefinition;
const typeDef = asVarDef.group === undefined ? varDef as unknown as ViewType : asVarDef.typeDefinition as ViewType;
const views = makeTypedArrayViews(typeDef, arrayBuffer, offset);
return {
...views,
set(data: any) {
set(data) {
setStructuredView(data, views.views);
},
};
Expand Down

0 comments on commit 4d3a13c

Please sign in to comment.