这是我的代码
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在打字稿中将对象限制为仅由其类型指定的属性。
当我在打字稿中使用Object.fromEntries(entries)orObject.entires(obj)来表示类型/常量entries数组或objt对象时,我会丢失类型any或广泛类型。
在某些情况下,我可以手动分配通用类型(例如Record<string, number>),但是设置每对/键的类型很繁琐。
这是我想要的一个例子。
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)
const myOldObject = {
x: 6,
y: "apple",
z: true
};
// The type of …Run Code Online (Sandbox Code Playgroud) 打字稿中有没有办法定义一个类型,它只是一个字符串文字,不包括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) 考虑以下代码,一个基类,两个子类,以及一个采用一个子类的一个实例的函数。
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 ×4
arrays ×1
branding ×1
class ×1
comparison ×1
instance ×1
literals ×1
object ×1
string ×1