Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance type safety in StructuredView #7

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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