小编Aid*_*din的帖子

是否可以将 typescript 对象限制为仅包含其类定义的属性?

这是我的代码

async getAll(): Promise<GetAllUserData[]> {
    return await dbQuery(); // dbQuery returns User[]
}

class User {
    id: number;
    name: string;
}

class GetAllUserData{
    id: number;
}
Run Code Online (Sandbox Code Playgroud)

getAll函数返回User[],并且数组的每个元素都有name属性,即使它的返回类型是GetAllUserData[]

我想知道是否可以out of the box在打字稿中将对象限制为仅由其类型指定的属性。

typescript

30
推荐指数
5
解决办法
2万
查看次数

如何在 Typescript 中获取输入的 Object.entries() 和 Object.fromEntries?

当我在打字稿中使用Object.fromEntries(entries)orObject.entires(obj)来表示类型/常量entries数组或objt对象时,我会丢失类型any或广泛类型。

在某些情况下,我可以手动分配通用类型(例如Record<string, number>),但是设置每对/键的类型很繁琐。

这是我想要的一个例子。

类型化 Object.fromEntries(entries)

const myArrayOfPairs = [["a", 5], ["b", "hello"], ["c", false]] as const;

// The type of the following is "any"
const myTypelessObject = Object.fromEntries(myArrayOfPairs);

// I want the type of this one to be: { a: 5; b: "hello"; c: false; }
const myTypedObject = createTypedObjectFromEntries(myArrayOfPairs); 
Run Code Online (Sandbox Code Playgroud)

类型化 Object.entries(obj)

const myOldObject = {
    x: 6,
    y: "apple",
    z: true
};

// The type of …
Run Code Online (Sandbox Code Playgroud)

arrays object typescript

16
推荐指数
2
解决办法
1万
查看次数

打字稿:强制类型为“字符串文字”而不是 &lt;string&gt;

问题

打字稿中有没有办法定义一个类型,它只是一个字符串文字,不包括string它自己?

请注意,我不是在谈论某个字符串文字列表;为此, 的简单联合"Value1" | "Value2"enum类型将起作用。我说的是任何字符串文字,但不是string它本身。

示例代码

type OnlyStringLiterals = ...; // <--- what should we put here?

const v1: OnlyStringLiterals = "hi"; // should work
const v2: OnlyStringLiterals = "bye"; // should work
// and so should be for any single string value assigned

// But:
const v3: OnlyStringLiterals = ("red" as string); // should NOT work -- it's string
Run Code Online (Sandbox Code Playgroud)

用例

我正在对代码中的类型进行品牌化,并将品牌名称作为模板传递给我的父类。请参阅下面的代码:

abstract class MyAbstractClass<
    BRAND_T …
Run Code Online (Sandbox Code Playgroud)

string branding literals typescript

7
推荐指数
2
解决办法
1718
查看次数

Typescript:如何期望精确的类实例作为函数参数

代码

考虑以下代码,一个基类,两个子类,以及一个采用一个子类的一个实例的函数。

abstract class AbstractNumberHolder {
    constructor(private readonly value: number) { }
    getValue() { return this.value; }
}

class UserId extends AbstractNumberHolder {
    equals(u: UserId) { return this.getValue() === u.getValue(); }
}

class SubscriptionCost extends AbstractNumberHolder {
    equals(s: SubscriptionCost) { return this.getValue() === s.getValue(); }
}

// ~~~

function printUserId(u: UserId) {
    console.log(u.getValue());
}

// ~~~

const subCost = new SubscriptionCost(50);
const uid = new UserId(1000105);

printUserId(subCost); // DOES NOT ERROR, WHILE IT SHOULD!
Run Code Online (Sandbox Code Playgroud)

上述代码的 Typescript Playground 链接) …

comparison class instance typescript

5
推荐指数
0
解决办法
1088
查看次数

标签 统计

typescript ×4

arrays ×1

branding ×1

class ×1

comparison ×1

instance ×1

literals ×1

object ×1

string ×1