Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript泛型:这里出了什么问题?_Typescript_Typescript Generics - Fatal编程技术网

Typescript泛型:这里出了什么问题?

Typescript泛型:这里出了什么问题?,typescript,typescript-generics,Typescript,Typescript Generics,我不能编译这种东西: type F<A> = (a:A)=>A; class CLAZZ<S extends { [k: string]: any }, K extends keyof S = keyof S>{ constructor(a:S){ this._o=a; } _o:S; set(k:K, f:F<S[K]>){ f(this._o[k]); } } type O = { pippo: numb

我不能编译这种东西:

type F<A> = (a:A)=>A;

class CLAZZ<S extends { [k: string]: any }, K extends keyof S = keyof S>{
  constructor(a:S){
    this._o=a;
  }
  _o:S;
  set(k:K, f:F<S[K]>){
     f(this._o[k]);
  }
}

type O = {
  pippo: number,
  pluto: string | null,
  paperino: {[k:string]:boolean}
}

let o = new CLAZZ<O>({"paperino":{}, pluto:null, pippo:1});

o.set("paperino", (paperino)=>({...paperino, "ciccio":true}))
F型

最后一行给出了此错误:

只能从对象类型创建排列类型

这是因为paperino参数被推断为

(参数)paperino:string | number |{ [k:string]:布尔;}空

而不仅仅是

{[k:string]:布尔;}

正如我所期待的

同时强制参数类型会给我一个错误

o、 集合(“paperino”,(paperino:{[k:string]:boolean})=>({……paperino,“ciccio”:true}))

类型为“(paperino:{[k:string]:布尔型)的参数; })=>{ciccio:true;}'不可分配给类型的参数 “F”。种类 参数“paperino”和“a”不兼容。 类型“string | number |{[k:string]:boolean;}| null”不可分配给类型“{[k:string]:boolean;}”。 类型“null”不可分配给类型“{[k:string]:boolean;}”


除……以外的任何解决方案。。。“any”

只需将键generic移动到
set
方法:

因为TS在创建对象时计算类型,而不是在调用
set
时计算类型,如果您希望在调用函数时缩小类型,您也可以将其设置为generic,类似于
set(k:K1,f:f)
的功能。(
CLAZZ
看起来有点拼写错误:D)