1、类型检测提示信息:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'
获取值get与设置值set
// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];
// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];
// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
obj[key];// badconst _setKeyValue = (key: string,value:any) => (obj: object) => obj[key]=value;
// betterconst _setKeyValue_ = (key: string,value:any) => (obj: Record<string, any>) =>
obj[key]=value;
// bestconst setKeyValue = <T extends object, U extends keyof T>(key: U,value:any) =>
(obj: T) => obj[key]=value;Bad - the reason for the error is the
objecttype is just an empty object by default. Therefore it isn't possible to use astringtype to index{}.Better - the reason the error disappears is because now we are telling the compiler the
objargument will be a collection of string/value (string/any) pairs. However, we are using theanytype, so we can do better.Best -
Textends empty object.Uextends the keys ofT. ThereforeUwill always exist onT, therefore it can be used as a look up value.
未完待续...