Skip to content

Instantly share code, notes, and snippets.

@YKalashnikov
Created September 24, 2023 22:49
Show Gist options
  • Save YKalashnikov/f09639986490b4346ef525c0c8a5c371 to your computer and use it in GitHub Desktop.
Save YKalashnikov/f09639986490b4346ef525c0c8a5c371 to your computer and use it in GitHub Desktop.
Generic Types
type Store = {
name: string;
age: number;
hobbies: string[];
};
function createStore<T extends Record<string, any>>(initialStore: T) {
const store = initialStore;
return {
get<K extends keyof Store>(key: K) {
return store[key];
},
set<K extends keyof Store>(key: K, value: T[K]) {
store[key] = value;
}
};
}
const store = createStore<Store>({
name: "Iurii",
age: 10,
hobbies: []
});
type MyStore = typeof store;
// type MyStore = ReturnType<typeof createStore<Store>>;
store.set("age", 50);
store.set("name", 435);
const age = store.get("age");
const name = store.get("name");
const hobbies = store.get("hobbies");
function Header(store: MyStore) {
store.get("age")
}
Header(store)
export default function App() {
return (
<div className="App">
<h1>Generic Types</h1>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment