gpt4 book ai didi

javascript - 动态 typescript 打字

转载 作者:行者123 更新时间:2023-11-30 11:46:09 28 4
gpt4 key购买 nike

有没有办法在 TypeScript 类中拥有动态对象属性,并为 TypeScript 添加动态类型?

我见过类似的问题,但没有一个像这样的完整示例 -

interface IHasObjectName {
objectName: string;
}

class example<A extends IHasObjectName, B extends IHasObjectName> {

constructor(a: A, b: B) {
this[a.objectName] = function() { return a; };
this[b.objectName] = function() { return b; }
}
}

class Cat implements IHasObjectName {
objectName: string = "";
}

class Dog implements IHasObjectName {
objectName: string = "";
}

let cat = new Cat();
cat.objectName = "Cat";

let dog = new Dog();
dog.objectName = "Dog";

let test = new example<Cat,Dog>(cat, dog);

// ??? TYPESCRIPT DOESN'T KNOW ABOUT THESE DYNAMIC PROPERTIES
// HOW DO I MAKE THIS WORK?
let d = test.Dog();
let c = test.Cat();

// I know I could access like this
// let d = test["Dog"]();
// but I want to access like function and have it typed

最佳答案

您可以使用工厂函数和 intersection :

function factory<A extends IHasObjectName, B extends IHasObjectName, C>(a: A, b: B): example<A, B> & C {
return new example<Cat, Dog>(a, b) as C;
}
var test = factory<Cat, Dog, { Dog(): Dog, Cat(): Cat }>(cat, dog);

var d = test.Dog(); // no error
var c = test.Cat(); // no error

( code in playground )


编辑

您不能“反射(reflect)”类型,因为它们在运行时不存在,但您可以使用传入实例的 constructor.name,因此您可以简单地这样做:

class example<A, B> {
constructor(a: A, b: B) {
this[a.constructor.name] = function() { return a; };
this[b.constructor.name] = function() { return b; }
}
}

class Cat {}

class Dog {}

var cat = new Cat();
var dog = new Dog();


function factory<A, B, C>(a: A, b: B): example<A, B> & C {
return new example<Cat, Dog>(a, b) as C;
}
var test = factory<Cat, Dog, { Dog(): Dog, Cat(): Cat }>(cat, dog);

var d = test.Dog();
var c = test.Cat();

( code in playground )

关于javascript - 动态 typescript 打字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40914716/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com