Typescript 是否有一个单行程序来实例化具有KeyOf style类型参数的对象?

Typescript 是否有一个单行程序来实例化具有KeyOf style类型参数的对象?,typescript,typescript-generics,Typescript,Typescript Generics,TypeScript允许我在这种类型的对象上分配myValue字段没有问题,但我不知道如何直接实例化其中一个对象并同时分配myValue interface FooInterface { myValue: number; } class FooClass implements FooInterface { myValue: number; } declare type ShortHandEqualType = string | number | boolean | Date; dec

TypeScript允许我在这种类型的对象上分配myValue字段没有问题,但我不知道如何直接实例化其中一个对象并同时分配myValue

interface FooInterface {
  myValue: number;
}

class FooClass implements FooInterface {
  myValue: number;
}

declare type ShortHandEqualType = string | number | boolean | Date;
declare type KeyOf<MT extends object> = Extract<keyof MT, string>;

type Bar<MT extends object> = {
  [P in KeyOf<MT>]?: (MT[P] & ShortHandEqualType);
}

function run<T extends FooInterface>(item: Bar<T>) {
  // Success
  item.myValue = 1;

  // Success
  const x: Bar<T> = {myValue: undefined};
  x.myValue = 2;

  // Success
  const y: Bar<T> = {};
  y.myValue = 3;

  // Error: Type '{ myValue: 4; }' is not assignable to type 'Bar<T>'
  const z: Bar<T> = {myValue: 4};
}
interface-foo接口{
myValue:数字;
}
类FooClass实现FooInterface{
myValue:数字;
}
声明类型ShorthandQualtype=string | number | boolean | Date;
声明类型KeyOf=Extract;
类型栏={
[P in KeyOf]?:(MT[P]&速记Qualtype);
}
功能运行(项目:条形图){
//成功
item.myValue=1;
//成功
常量x:Bar={myValue:undefined};
x、 myValue=2;
//成功
常数y:Bar={};
y、 myValue=3;
//错误:类型“{myValue:4;}”不能分配给类型“Bar”
常量z:Bar={myValue:4};
}

我尝试将字段设置为非可选字段,但没有任何帮助。

这是TS不一致的地方之一;从技术上讲,这应该是一个错误,因为您可能将类型为
{myValue:1 | 2 | 3}
的a值传递为
T
,并且
{mvValue:4}
的输出不可分配给该类型。它允许您执行
const z:Bar={};z、 myValue=4
只是TS不一致。如果您只是想进行赋值而不担心,请使用类型断言,如
const z={myValue:4}as Bar
。我几乎可以肯定这个问题以前有人问过,但我还没有找到一个非常具体的重复项Yet这里总是有@jcalz可以肯定地说你永远不能安全地分配给一个函数中的一个字段,这个函数不知道对象的确切类型吗?您永远不知道哪一组值对任何字段都是有效的,这似乎很有限制性。