我们在项目中这样使用它(方法略有不同):
interface ImmutableMap<T> extends Map<string, any> {
get<K extends keyof T>(name: K): T[K];
}
我们使用的是旧版本Immutable.js
尚未使用映射类型的类型(T[K]
)。 AFAIK 类型从那时起已更新,无需覆盖get
method.
编辑:实际上get
与上面的方法不同,方法仍然不是完全类型安全的。所以重写该方法还是有它的优点的。
通过上面的声明,您可以创建不可变的映射,例如:
type AuthState = ImmutableMap<{
user:string|null;
loggedIn:boolean;
}>;
const authState:AuthState = fromJS({ user: 'Alice', loggedIn: true });
理想情况下,您希望这样输入:
/**
* Imaging these are typings for your favorite immutable
* library. We used it to enhance typings of `immutable.js`
* with the latest TypeScript features.
*/
declare function Immutable<T>(o: T): Immutable<T>;
interface Immutable<T> {
get<K extends keyof T>(name: K): T[K];
set<S>(o: S): Immutable<T & S>;
}
const alice = Immutable({ name: 'Alice', age: 29 });
alice.get('name'); // Ok, returns a `string`
alice.get('age'); // Ok, returns a `number`
alice.get('lastName'); // Error: Argument of type '"lastName"' is not assignable to parameter of type '"name" | "age"'.
const aliceSmith = alice.set({ lastName: 'Smith' });
aliceSmith.get('name'); // Ok, returns a `string`
aliceSmith.get('age'); // Ok, returns a `number`
aliceSmith.get('lastName'); // Ok, returns `string`
链接到游乐场
为了实现上述目标Immutable.js
您可以创建一个小辅助函数,其唯一目的是“修复”打字:
import { fromJS } from 'immutable';
interface Immutable<T> {
get<K extends keyof T>(name: K): T[K];
set<S>(o: S): Immutable<T & S>;
}
function createImmutable<T extends object> (o:T) {
return fromJS(o) as Immutable<T>;
}
请注意,我使用了fromJS
在示例中。这将创建一个Map
只要传递的输入是Object
。使用的好处fromJS
over Map
是打字更容易被覆盖。
旁注:您可能还想研究一下Record
s.