来自接口的打字稿只读参数



如何确保state是只读的,但不是它的每个键(否则可以使用ReadOnly.所有这些都来自界面,我对打字稿 5 (例如 const 类型)没问题。

export type GameDeviceFactory<State, Events extends { in: unknown; out: unknown }> = (
state: State,
emitEvent: (event: Events["out"]) => Promise<void>,
) => any;
const Some: GameDeviceFactory<{a: string}, { in: unknown; out: unknown }> = (state) => {
state = {a: ""} // Should yield
state.a = "" // Should be OK
}

重现

谢谢

编辑:还添加了这个

type UnknownEventsInterface = { in: JSONObject; out: JSONObject };
type FactoryArgs<State, Events extends UnknownEventsInterface> = {
readonly state: State;
readonly emitEvent: (event: Events["out"]) => Promise<void>;
};
export type GameDeviceFactory<State, Events extends UnknownEventsInterface> = (
args: FactoryArgs<State, Events>,
) => IGameDevice<Events>;

但是,虽然你不能覆盖args.state但如果你像({state})一样重组它,你可以自由地覆盖解构的。

你在找 https://eslint.org/docs/latest/rules/no-param-reassign 吗?

对声明为函数参数的变量的赋值可能会产生误导并导致混淆行为,因为修改函数参数也会改变参数对象。通常,函数参数的赋值是无意的,表示错误或程序员错误。

更多的是关于代码风格,然后是关于打字

还有另一种称为品牌的技术,它允许我们实现名义类型而不是结构类型。

type Brand<T> = T & { __brand: "brand"}
export type GameDeviceFactory<
State,
> = (state: Brand<State>) => any;
const Some: GameDeviceFactory<{ a: string }> = (
state
) => {
state = { a: "" }; // Correctly raise an error
};

这是因为 from{ a: "" }缺少__brand属性。

但是,请记住,这不是您的问题的解决方案,因为如果您添加所有属性,您仍然可以正确分配新值。

state = { a: "", __brand: "brand" }; // Can correctly assign

正如其他评论所指出的,目前在TypeScript中不可能实现参数的恒定性。