[英]Generic in function doesn't check argument type in Typescript
我期待打字稿會引發錯誤,因為我在EntryPoints
傳遞了錯誤數量的元素,但它不會發生。
function createContext<T>(defaultValue: T): T[] {
return [defaultValue]
}
interface EntryPoints {
parentSelector: string;
}
interface SomeType {
entryPoints: EntryPoints[];
}
const defaultData = {
entryPoints: [{
parentSelector: '',
foo: 1 // <-- expecting error here
}]
}
createContext<SomeType>(defaultData)
沒有通用的相同代碼按預期工作
function createContext<T>(defaultValue: T): T[] {
return [defaultValue]
}
interface EntryPoints {
parentSelector: string;
}
interface SomeType {
entryPoints: EntryPoints[];
}
const defaultData: SomeType = {
entryPoints: [{
parentSelector: '',
foo: 1 // <-- throwing error here
}]
}
createContext(defaultData)
您遇到了對象新鮮度問題,因此允許使用其他密鑰。
如果您明確傳遞了該對象,則將對其進行正確的鍵入檢查:
function createContext<T>(defaultValue: T): T[] {
return [defaultValue];
}
interface EntryPoints {
parentSelector: string;
}
interface SomeType {
entryPoints: EntryPoints[];
}
createContext<SomeType>({
entryPoints: [
{
parentSelector: "",
foo: 1 // <-- errors as expected here
}
]
});
你遇到的是兩者之間的區別
考慮一下我們有兩種類型。 其中一個財產比另一個財產多一個。
type Foo = {
foo: string;
};
type FooBar = {
foo: string;
bar: string;
};
將對象文字指定給類型時, 不允許使用其他屬性 。
// Object literal may only specify known properties,
// and 'bar' does not exist in type 'Foo'.
const foo: Foo = {
foo: "foo",
bar: "bar" // <---- bar is not allowed on Foo.
};
將變量分配給類型時, 允許使用其他屬性 。
const fooBar: FooBar = {
foo: "foo",
bar: "bar" // <---- bar is going to be allowed on Foo
};
const foo: Foo = fooBar; // <---- see, no error
將fooBar
分配給foo
是可以的,因為fooBar
是一個不是對象文字的變量,因此可以包含未知屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.