在Typescript中,可以使用泛型添加属性键?

在Typescript中,可以使用泛型添加属性键?,typescript,Typescript,在typescript中,可以使用泛型添加属性键 function f<T extends string>(k: T) { return { [k]: 'test'; }; } const obj = f('foo'); // some how assert that obj.foo exists 有什么想法吗?这是不可能的吗?是的,这是可能的,使用和的创造性组合 您可以使用映射类型对“任意字符串文字键控属性”案例进行建模 type F<Keys extends str

在typescript中,可以使用泛型添加属性键

function f<T extends string>(k: T) {
  return { [k]: 'test'; };
}

const obj = f('foo');
// some how assert that obj.foo exists

有什么想法吗?这是不可能的吗?

是的,这是可能的,使用和的创造性组合

您可以使用映射类型对“任意字符串文字键控属性”案例进行建模

type F<Keys extends string> = {
    [K in Keys] : number;
}

const f : F<'bar'> = null;
f.bar;  // typed as a number
f.wibble;  // type error
type F<Keys extends string> = {
    [K in Keys] : number;
}

const f : F<'bar'> = null;
f.bar;  // typed as a number
f.wibble;  // type error
type F<Keys extends string> = {
    [K in Keys] : number;
} & {
    additionalKey1 : object;
    additionalKey2 : string;
}
const f : F<'bar'> = null;
f.bar;  // typed as a number
f.additionalKey1;  // typed as an object