답변:
JavaScript (및 TypeScript)의 모든 필드는 null또는 값을 가질 수 있습니다 undefined.
널 입력 가능과 다른 필드를 선택적으로 만들 수 있습니다 .
interface Employee1 {
name: string;
salary: number;
}
var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK
// OK
class SomeEmployeeA implements Employee1 {
public name = 'Bob';
public salary = 40000;
}
// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
public name: string;
}
다음과 비교하십시오 :
interface Employee2 {
name: string;
salary?: number;
}
var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number
// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
public name = 'Bob';
}
"strict" : false
salary:number|null;당신이 할 경우, salary?:number; salary = null;당신은 오류가 발생합니다. 그러나이 salary = undefined;경우에는 잘 작동합니다. 솔루션 : Union 즉 '|'사용
이 경우 유니온 유형이 최선의 선택입니다.
interface Employee{
id: number;
name: string;
salary: number | null;
}
// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };
편집 : 예상대로 작동하려면 strictNullChecks in을tsconfig .
더 C # 처럼 하려면 다음 과 같이 Nullable유형을 정의하십시오 .
type Nullable<T> = T | null;
interface Employee{
id: number;
name: string;
salary: Nullable<number>;
}
보너스:
Nullable내장 된 Typescript 유형처럼 동작 하려면 global.d.ts루트 소스 폴더 의 정의 파일에서 정의하십시오. 이 길은 나를 위해 일했다 :/src/global.d.ts
emp: Partial<Employee>, 우리가 할 수 emp.id있거나 할 수는 emp.name있지만 우리가 emp: Nullable<Employee>할 수 없다면 할 수 없습니다emp.id
?옵션 필드에 물음표 를 추가하십시오 .
interface Employee{
id: number;
name: string;
salary?: number;
}
다음과 같이 사용자 정의 유형을 구현할 수 있습니다.
type Nullable<T> = T | undefined | null;
var foo: Nullable<number> = 10; // ok
var bar: Nullable<number> = true; // type 'true' is not assignable to type 'Nullable<number>'
var baz: Nullable<number> = null; // ok
var arr1: Nullable<Array<number>> = [1,2]; // ok
var obj: Nullable<Object> = {}; // ok
// Type 'number[]' is not assignable to type 'string[]'.
// Type 'number' is not assignable to type 'string'
var arr2: Nullable<Array<string>> = [1,2];
void가 같은 유형의 질문을 가지고 있습니다. void는 모든 유형의 하위 유형이기 때문에 (예 : scala와는 달리) ts의 모든 유형은 nullable입니다.
이 흐름도가 도움이되는지 확인하십시오-https: //github.com/bcherny/language-types-comparison#typescript
void'모든 유형의 하위 유형'(인 바닥 유형 )를 참조하십시오 이 스레드 . 또한 스칼라에 제공 한 차트도 올바르지 않습니다. Nothing스칼라에서 실제로는 바닥 유형입니다. scala 는 typescript, atm에 bottom 유형 이 없습니다 .
널 입력 가능 유형은 런타임 오류를 호출 할 수 있습니다. 그래서 컴파일러 옵션을 사용하고 유형으로 --strictNullChecks선언 하는 것이 좋습니다 number | null. 또한 중첩 함수의 경우 입력 유형이 null이지만 컴파일러가 중단 할 수있는 것을 알 수 없으므로 사용 !(exclamination mark)을 사용하는 것이 좋습니다 .
function broken(name: string | null): string {
function postfix(epithet: string) {
return name.charAt(0) + '. the ' + epithet; // error, 'name' is possibly null
}
name = name || "Bob";
return postfix("great");
}
function fixed(name: string | null): string {
function postfix(epithet: string) {
return name!.charAt(0) + '. the ' + epithet; // ok
}
name = name || "Bob";
return postfix("great");
}
참고. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions
typescript@next현재)