Skip to content

Instantly share code, notes, and snippets.

View Gfast2's full-sized avatar
🚩

Su Gfast2

🚩
View GitHub Profile
@Gfast2
Gfast2 / usingTypeParametersInTypeConstrain.ts
Created March 24, 2020 07:56
You can declare a type parameter that is constrained by another type parameter. For example, here we’d like to get a property from an object given its name. We’d like to ensure that we’re not accidentally grabbing a property that does not exist on the obj, so we’ll place a constraint between the two types:
// https://www.typescriptlang.org/docs/handbook/generics.html
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a"); // okay
getProperty(x, "m"); // error: Argument of type 'm' isn't assignable to 'a' | 'b' | 'c' | 'd'.
@Gfast2
Gfast2 / ReactComponentSizing.tsx
Created May 15, 2020 08:47
A Way to read a react component size with resize eventhandler
class DivSize extends React.Component {
constructor(props) {
super(props)
this.state = {
width: 0
}
this.resizeHandler = this.resizeHandler.bind(this);
}