Skip to content

Instantly share code, notes, and snippets.

@Announcement
Created May 15, 2019 17:41
Show Gist options
  • Save Announcement/de0d2c35dd7ffd5dd484816635b23ea7 to your computer and use it in GitHub Desktop.
Save Announcement/de0d2c35dd7ffd5dd484816635b23ea7 to your computer and use it in GitHub Desktop.
why is {[key: string]: T} not { x: number }
interface Matrix {
readonly [index: number]: {
readonly [index: number]: number;
};
}
interface CartesianPoint {
x: number;
y: number;
z: number;
}
function generateMatrix_nPoints(...points: CartesianPoint[]): Matrix {
return [
[...points.map(property('x'))],
[...points.map(point => point.y)],
[...points.map(point => point.z)]
];
}
function property (name: string) {
return function<T> (input: { [key: string]: T }): T {
return input[name];
}
}
@Aankhen
Copy link

Aankhen commented May 15, 2019

You’ll have to defer the checking to runtime and cast it manually:

function generateMatrix_nPoints(...points: CartesianPoint[]): Matrix {
  return [
    [...points.map(property('x')) as number[]],
    [...points.map(point => point.y)],
    [...points.map(point => point.z)]
  ];
}

function property (name: string) {
    return function(input: object): any {
      if (!(name in input)) {
          throw new Error(`No ${name} in ${input}`);
      }

      return input[name];
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment